SQL Server Group由guid提供,但最近在组中命令整个查询

时间:2012-10-16 21:11:53

标签: sql sql-server

我有一个查询,我想通过某个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]

1 个答案:

答案 0 :(得分:1)

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

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