views:

60

answers:

1

Hello, I have a single user table and I'm trying to come up with a query that returns the total count of all users grouped by date along with the total count of users grouped by date who are of a specific client.

Here is what I have thus far, where there's the total count of users grouped by date, but can't seem to figure out how to get the count of those users where user.client_id = x

SELECT user.created,
COUNT(user.id) AS overall_count
FROM user
GROUP BY DATE(user.created)

trying for a row result like this:

[created] => 2010-05-15 19:59:30
[overall_count] => 10
[client_count] => (some fraction of overall count, the number of users where 
                   user.client_id = x grouped by date)
+4  A: 

This should do the trick for MySQL:

SELECT
  user.created,
  COUNT(user.id) AS overall_count,
  SUM(user.client_id = x) AS client_count
FROM user
GROUP BY DATE(user.created)

The boolean expression user.client_id = x returns 1 if it is true and 0 if not, so you can just sum them up.


With another database you would do

SUM( CASE WHEN user.client_id = x THEN 1 ELSE 0 END ) AS client_count
Peter Lang
that's it-- thank you!
twmulloy