views:

67

answers:

2

I'm trying to do a lookup on our demographioc table to display some stats. However, since out demographic table is quit big I want to do it in one query.

There are 2 fields that are important: sex, last_login

I want to be able to get the total number of logins for various date ranges (<1day ago, 1-7 days ago, 7-30 days ago, etc) GROUPED BY sex

I right now know how to do it for one date range. For example less than 1 day ago:

SELECT sex, count(*) peeps 
  FROM player_account_demo 
 WHERE last_demo_update > 1275868800 
GROUP BY sex

Which returns:

sex       peeps
----------------
UNKNOWN   22
MALE      43
FEMALE    86

However I'd have to do this once for each range. Is there a way to get all 3 ranges in there?

I'd want my end result to look something like this:

sex       peeps<1day      peeps1-7days       peeps7-30days

Thanks!

IMPORTANT NOTE: last demo_update is the epoch time (unix time stamp)

A: 

You want to use a Pivot Table.

VeeArr
A pivot table is for display right? I want to be able to select everything in 1 query without having to select the whole table and doing it all in php.
darudude
This is not a concept supported by the query language. If you really want to do it, you can hack together a case-by-case check in your `SELECT` statement (e.g. see Wrikken's response).
VeeArr
`PIVOT` and `UNPIVOT` are ANSI I believe, but only supported on SQL Server 2005+ and Oracle 11g+. CASE is ANSI-92 for that matter...
OMG Ponies
According to the OP's tags, his question is in regards to mySQL, which (to my knowledge) does not implement any pivot table functionality.
VeeArr
+2  A: 
SELECT sex,
  SUM(IF(DATEDIFF(NOW(),last_login) < 1,1,0)),
  SUM(IF(DATEDIFF(NOW(),last_login) BETWEEN 1 AND 7,1,0)),
  SUM(IF(DATEDIFF(NOW(),last_login) BETWEEN 7 AND 30,1,0))
FROM player_account_demo 
GROUP BY sex
Wrikken
Thx this got me on the right track
darudude