Search code examples
mysqlsql

MYSQL - SELECT NULL otherwise latest DATE per group


I have the following data in my database:

| ID   | FK_ID  | MODEL | DATE              | 
+------+--------+-------+-------------------+
|1     | 11     | m1    |NULL               |
|2     | 11     | m1    |NULL               |
|3     | 11     | m2    |2019-05-08 12:04:24|
|4     | 11     | m2    |2019-05-08 12:07:43|
|5     | 11     | m2    |2019-05-08 12:08:37|
|6     | 11     | m3    |2019-05-08 12:13:19|
|7     | 11     | m3    |NULL               |
|8     | 12     | m7    |2019-05-08 12:04:14|

I want to get the latest DATE of each MODEL, but if the DATE is null for a MODEL then I want to get the NULL instead of latest date.

Expected Output

| MODEL | DATE              |
+-------+-------------------+
| m1    |NULL               |
| m2    |2019-05-08 12:08:37|
| m3    |NULL               |

I tried the below query:

SELECT MODEL, DATE FROM MODEL_TABLE
WHERE FK_ID = 11 AND (DATE IN ( 
    SELECT MAX(DATE)
    FROM MODEL_TABLE
    GROUP BY MODEL
) OR DATE IS NULL)
GROUP BY MODEL;

But I am getting the below result:

Actual Output (Wrong)

| MODEL | DATE              |
+-------+-------------------+
| m1    |NULL               |
| m2    |2019-05-08 12:08:37|
| m3    |2019-05-08 12:13:19|

Can someone let me know how can correct the query to fetch the expected result


Solution

  • count(*) counts all rows, count(date) counts non-null values. If they are the same, no null exists, i.e. return max(date), else return null.

    SELECT MODEL, case when count(*) = count(DATE) then max(DATE) end
    FROM MODEL_TABLE
    group by MODEL