Created
June 19, 2018 04:23
-
-
Save MatheusR42/5b436f33c4e2956870b39fdab173d592 to your computer and use it in GitHub Desktop.
Include NULL values in aggregate function COUNT() in MySQL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE TABLE example_table ( | |
hour INT | |
); | |
INSERT INTO example_table (hour) | |
VALUES (1),(2),(2),(NULL),(NULL),(NULL); | |
COMMIT; | |
SELECT | |
COUNT(DISTINCT hour) + (CASE | |
WHEN COUNT(hour) <> COUNT(*) THEN 1 | |
ELSE 0 | |
END) AS 'distinct hours' | |
FROM | |
example_table; | |
SELECT | |
hour, COUNT(*) AS 'count' | |
FROM | |
example_table | |
GROUP BY hour; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
SQL Fiddle: http://sqlfiddle.com/#!9/2b326d/1