简体   繁体   中英

mysql group by dates and null values

I have a problem with mysql because I would like to group by some dates and some null values but the result wasn't the expected. My target is reducing the number of rows of the table but not the number of dates.

The starting table is that one:

+------+---------------------+---------------------+---------------------+--+
| Col1 |        Date1        |        Date2        |        Date3        |  |
+------+---------------------+---------------------+---------------------+--+
| A    | NULL                | 2016-10-27 16:27:22 | NULL                |  |
| A    | NULL                | NULL                | 2012-10-11 07:07:32 |  |
| B    | NULL                | 2016-01-27 16:27:22 | NULL                |  |
| B    | 2016-10-17 16:07:32 | NULL                | NULL                |  |
| C    | NULL                | 2014-10-17 16:07:32 | 2011-10-17 16:57:32 |  |
+------+---------------------+---------------------+---------------------+--+

I would like to group this table by Col1 to obtain the following output:

+------+---------------------+---------------------+---------------------+
| Col1 |        Date1        |        Date2        |        Date3        |
+------+---------------------+---------------------+---------------------+
| A    | NULL                | 2016-10-27 16:27:22 | 2012-10-11 07:07:32 |
| B    | 2016-10-17 16:07:32 | 2016-01-27 16:27:22 | NULL                |
| C    | NULL                | 2014-10-17 16:07:32 | 2011-10-17 16:57:32 |
+------+---------------------+---------------------+---------------------+

I tried with the following query but it didn't work as expected::

SELECT *
FROM table1
GROUP BY Col1

Can someone help me fixing the query?

When grouping, you should apply an aggregation function to all the columns that you want to select but are not in the group by . This is not mandatory in the latest versions of MySQL, but in a vast majority of cases it's what you need.

This query should give you the desired output for the sample input you provided, but you may need different aggregation functions if the input is different.

SELECT  Col1, max(Date1), max(Date2), max(Date3)
FROM    table1
GROUP BY Col1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM