Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

mysql

count

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)
like image 818
skilleo Avatar asked May 16 '10 06:05

skilleo


1 Answers

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
like image 152
Peter Lang Avatar answered Sep 20 '22 07:09

Peter Lang