开发者

SQL for total count and count within that where condition is true

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)


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜