Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL group by with rollup, coalesce/ifnull, and date functions

Tags:

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?

like image 687
Dmitriy P. Avatar asked Jul 26 '16 04:07

Dmitriy P.


People also ask

Does coalesce work with GROUP BY?

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 .

What is the difference between coalesce and Ifnull?

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.

What does coalesce function do in MySQL?

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.

Can we use two GROUP BY in same query?

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'.


1 Answers

If you're trying to target the NULL's generated during the aggregate rollup calculations (as opposed to NULLs in your raw data), you're referring to the wrong NULLs. 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.

like image 177
Unix One Avatar answered Sep 28 '22 03:09

Unix One