+--------------+-----------------+-----------+---------------------+
| 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 and 4 has same "parent_of" 2. I want to select only one from them which has max date.
My Expected Result is:
+--------------+-----------------+-----------+---------------------+
| 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 |
+--------------+-----------------+-----------+---------------------+
you can select max of created_date and then group by parent_of. A query will look like this
SELECT max(hierarchy_id) as hierarchy_id,title,parent_of,max(created_date) as created_date
FROM tableName
GROUP BY parent_of
If we assume that the ids are assigned in ascending order, then you can just use max()
on the first and last columns:
select max(hierarchy_id) as hierarchy_id, title, parent_of, max(created_date) as created_date
from table t
group by title, parent_of;
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.