我的表格如下(根据GrandParent
,Parent
和Child
分组):
Child | Parent | GrandParent | Date
---------------------------------------------------
2 | 1 | 1 | 2015-11-04 01:30:22
3 | 1 | 1 | 2015-11-05 01:30:22
4 | 4 | 4 | 2015-11-04 01:31:41
5 | 5 | 5 | 2015-11-04 01:31:41
7 | 7 | 7 | 2014-08-19 03:45:01
88 | 8 | 8 | 2014-08-19 03:45:01
90 | 8 | 8 | 2014-08-19 03:45:01
97 | 8 | 8 | 2015-03-18 03:45:01
704 | 8 | 8 | 2015-03-18 03:45:01
27 | 11 | 9 | 2015-10-22 06:42:30
28 | 11 | 9 | 2015-10-24 06:42:30
30 | 12 | 9 | 2015-11-15 06:42:30
31 | 12 | 9 | 2015-11-16 06:42:30
没有Child
的 Parent
会将自己视为Parent
和GrandParent
。
我的目标是订购上表:
GrandParent
群组应位于顶部GrandParent
内,最近日期的Parent
群组应位于顶部Parent
内,最近日期的Child
应位于顶部结果应为:
Child | Parent | GrandParent | Date
---------------------------------------------------
31 | 12 | 9 | 2015-11-16 06:42:30
30 | 12 | 9 | 2015-11-15 06:42:30
28 | 11 | 9 | 2015-10-24 06:42:30
27 | 11 | 9 | 2015-10-22 06:42:30
3 | 1 | 1 | 2015-11-05 01:30:22
2 | 1 | 1 | 2015-11-04 01:30:22
4 | 4 | 4 | 2015-11-04 01:31:41
5 | 5 | 5 | 2015-11-04 01:31:41
97 | 8 | 8 | 2015-03-18 03:45:01
704 | 8 | 8 | 2015-03-18 03:45:01
88 | 8 | 8 | 2014-08-19 03:45:01
90 | 8 | 8 | 2014-08-19 03:45:01
7 | 7 | 7 | 2014-08-19 03:45:01
答案 0 :(得分:3)
在ORDER BY中使用子查询。
select child, parent, grandparent, date
from mytable
order by
(select max(date) from mytable grp where grp.grandparent = mytable.grandparent) desc,
(select max(date) from mytable grp where grp.parent = mytable.parent) desc,
date desc;
答案 1 :(得分:1)
我想你想要这样的东西:
select t1.* from @t t1
join (select grandparent, max(date) as date from @t group by grandparent) t2
on t2.grandparent = t1.grandparent
join (select parent, max(date) as date from @t group by parent) t3
on t3.parent = t1.parent
order by t2.date desc, t3.date desc, t1.date desc
您正在加入包含2套的初始表,其中第一组表示每granparent
的最大日期,第二组表示每parents
的最大日期。