0

我有一个查询,我想按某个 GUID 对事物进行分组,但我想按日期排序一个组(简单),然后根据每个组中的最新记录对整个结果集进行排序,并列出该顺序作为结果集。我想让他们粘在一起。那有意义吗?

我能想到的最好的是:

SELECT 
   ID, data, Date, 
   row_number() OVER (PARTITION BY GUID ORDER BY Date DESC) AS rn 
FROM 
   MyTable

但这并没有考虑到整个结果集的日期。

默认表

ID      data                Date                        GUID
0       mapper started      2012-10-16 12:18:52     SessionID:[376f795a-dba2-49e1-8047-dbac9141d78b]
1       view models init    2012-10-16 12:18:53     SessionID:[2a1be1ce-606a-44ca-8400-75b7fd23d09a]
2       view load           2012-10-16 12:18:54     SessionID:[2a1be1ce-606a-44ca-8400-75b7fd23d09a]
3       mapper load         2012-10-16 12:18:55     SessionID:[376f795a-dba2-49e1-8047-dbac9141d78b]
4       view finished       2012-10-16 12:18:56     SessionID:[2a1be1ce-606a-44ca-8400-75b7fd23d09a]
5       mapper finished     2012-10-16 12:18:57     SessionID:[376f795a-dba2-49e1-8047-dbac9141d78b]

我想要的查询输出:

ID      data                Date                         GUID
5       mapper finished     2012-10-16 12:18:57     SessionID:[376f795a-dba2-49e1-8047-dbac9141d78b]
3       mapper load         2012-10-16 12:18:55     SessionID:[376f795a-dba2-49e1-8047-dbac9141d78b]
0       mapper started      2012-10-16 12:18:52     SessionID:[376f795a-dba2-49e1-8047-dbac9141d78b]
4       view finished       2012-10-16 12:18:56     SessionID:[2a1be1ce-606a-44ca-8400-75b7fd23d09a]
2       view load           2012-10-16 12:18:54     SessionID:[2a1be1ce-606a-44ca-8400-75b7fd23d09a]
1       view models init    2012-10-16 12:18:53     SessionID:[2a1be1ce-606a-44ca-8400-75b7fd23d09a]
4

1 回答 1

2

花了一段时间,但它似乎有效:

select y.id, y.data, y.date, y.guid
from
  (select max(a.date) as date, a.guid
    from mytable a
    group by a.guid)x,
  (select id, data, date, guid, 
    row_number() over(partition by guid order by guid) as rn 
    from MyTable)y
where x.guid = y.guid
order by x.date desc, y.date desc;

SQL 小提琴: http ://sqlfiddle.com/#!3/1cdc1/59

于 2012-10-16T22:54:53.677 回答