SUMing the results of a COUNT() in MySQL

时间:2016-07-11 19:35:09

标签: mysql sql

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+

2 个答案:

答案 0 :(得分:2)

Use COUNT(DISTINCT):

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

答案 1 :(得分:0)

I do not think this requires a UNION

SELECT some_id, SUM(1) as cnt, some_date
FROM some_table
GROUP BY some_id, some_date
WITH ROLLUP

Here is a test.