randombits randombits - 4 months ago 9
MySQL Question

SUMing the results of a COUNT() in MySQL

Is a UNION query required to achieve the following. I have a table with data that looks like this:

some_id | some_date
--------------------
5 | 2016-04-03
3 | 2016-04-03
2 | 2016-04-03
5 | 2016-04-03


I'd like to get the total number of times we've seen any and all ID for the date
2016-04-03
. So the SUM would be 3 here, with 5 having a count of 2, 3 having a count of 1, 2 having a count of 1.

Is a UNION required to make this work?

This is using MySQL 5.6+

Answer

Use COUNT(DISTINCT):

SELECT COUNT(DISTINCT some_id)
FROM YourTable
WHERE some_date = '2016-04-03'