I have run into an issue with MySQL's ROLLUP and dealing with the resulting NULLs. The IFNULL/COALESCE functions work well with plain columns, but seem to break down when used with date functions. Examples follow:
SELECT
YEAR(date_time) AS Year,
count(x) AS Count
FROM mytable
GROUP BY year WITH ROLLUP
returns (as expected)
Year Count
---- -----
2015 3
2016 2
NULL 5
When I query for non-date columns (varchar, for example), I can deal with the NULL values by using IFNULL or COALESCE functions to replace NULL values with strings. However, when I apply the same logic to the above query, it does not seem to work.
SELECT
COALESCE(YEAR(date_time), 'moo') AS Year,
count(x) AS Count
FROM mytable
GROUP BY year WITH ROLLUP
or
SELECT
IFNULL(YEAR(date_time), 'moo') AS 'year',
count(x) AS Count
FROM mytable
GROUP BY year WITH ROLLUP
returns
Year Count
---- -----
2015 3
2016 2
NULL 5
instead of expected
Year Count
---- -----
2015 3
2016 2
moo 5
Any ideas, suggestions?
Because the COALESCE is an expression, you can use it in any clause that accepts an expression such as SELECT , WHERE , GROUP BY , and HAVING .
ifnull can only replace a null value of the first parameter. Whereas coalesce can replace any value with another value. With coalesce in standard SQL you can have many parameters transforming many values.
The MySQL COALESCE() function is used for returning the first non-null value in a list of expressions. If all the values in the list evaluate to NULL, then the COALESCE() function returns NULL. The COALESCE() function accepts one parameter which is the list which can contain various values.
Yes, it is possible to use MySQL GROUP BY clause with multiple columns just as we can use MySQL DISTINCT clause. Consider the following example in which we have used DISTINCT clause in first query and GROUP BY clause in the second query, on 'fname' and 'Lname' columns of the table named 'testing'.
If you're trying to target the NULL
's generated during the aggregate rollup calculations (as opposed to NULL
s in your raw data), you're referring to the wrong NULL
s. If so, this is probably what you are trying to do:
SELECT
IFNULL(m.year, 'moo')
FROM
(SELECT
YEAR(date_time) AS 'year'
FROM
mytable
GROUP BY
year
WITH ROLLUP) m
Here's the sqlfiddle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With