MySQL:分组依据和按日期排序

时间:2014-11-16 14:44:54

标签: mysql select group-by sql-order-by

+--------------+-----------------+-----------+---------------------+
| hierarchy_id | title           | parent_of | created_date        |
+--------------+-----------------+-----------+---------------------+
|            1 | Muscat          |         0 | 2014-01-01 00:00:00 |
|            2 | Bahrain         |         1 | 2014-01-01 00:00:00 |
|            3 | Kuwait          |         2 | 2014-01-01 00:00:00 |
|            4 | Jordan          |         2 | 2014-01-25 00:00:00 |
+--------------+-----------------+-----------+---------------------+

hierarchy_id 3和4具有相同的“parent_of”2。 我想只选择一个有最大日期的人。

我的预期结果是:

+--------------+-----------------+-----------+---------------------+
| hierarchy_id | title           | parent_of | created_date        |
+--------------+-----------------+-----------+---------------------+
|            1 | Muscat          |         0 | 2014-01-01 00:00:00 |
|            2 | Bahrain         |         1 | 2014-01-01 00:00:00 |
|            4 | Jordan          |         2 | 2014-01-25 00:00:00 |
+--------------+-----------------+-----------+---------------------+

2 个答案:

答案 0 :(得分:1)

您可以选择max_create_date,然后按parent_of分组。查询将如下所示

SELECT max(hierarchy_id) as hierarchy_id,title,parent_of,max(created_date) as created_date  
FROM tableName
GROUP BY parent_of

答案 1 :(得分:0)

如果我们假设按升序分配ID,那么您可以在第一列和最后一列使用max()

select max(hierarchy_id) as hierarchy_id, title, parent_of, max(created_date) as created_date  
from table t
group by title, parent_of;