带有分组的SQL ORDER BY

时间:2011-08-25 17:22:18

标签: sql sql-server-2008

我有以下查询

SELECT Id, Request, BookingDate, BookingId FROM Table ORDER BY Request DESC, Date

如果一行有类似的ForeignKeyId,我希望它在下一个有序行之前进入,如:

Request         Date  ForeignKeyId
Request3    01-Jun-11   56
Request2    03-Jun-11   89
NULL        03-Jun-11   89
Request1    05-Jun-11   11
NULL        20-Jul-11   57

我一直在看RANK和OVER,但还没有找到一个简单的修复。

修改

我上面编辑过来使用Andomar的答案中的以下查询显示实际字段和粘贴数据

select  *
from    (
        select  row_number() over (partition by BookingId order by Request DESC) rn 
        ,       Request, BookingDate, BookingID
        from    Table
        WHERE Date = '28 aug 11'
        ) G
order by
     rn   
,       Request DESC, BookingDate 

1   ffffff  23/01/2011 15:57    350821
1   ddddddd 10/01/2011 16:28    348856
1   ccccccc 13/09/2010 14:44    338120
1   aaaaaaaaaa  21/05/2011 20:21    364422
1   123 17/09/2010 16:32    339202
1       NULL    NULL
2   gggggg  08/12/2010 14:39    346634
2       NULL    NULL
2       17/09/2010 16:32    339202
2   NULL    10/04/2011 15:08    361066
2   NULL    02/05/2011 14:12    362619
2   NULL    11/06/2011 13:55    366082
3       NULL    NULL
3       16/10/2010 13:06    343023
3       22/10/2010 10:35    343479
3       30/04/2011 10:49    362435

预订ID 339202应该彼此相邻但不是

1 个答案:

答案 0 :(得分:2)

您可以通过ForeignKeyId partition,然后将每个第二行或更低的行排在他们的“头部”下方。将“head”定义为ForeignKeyId的第一行。例如,在Request上排序:

; with  numbered as 
        (
        select  row_number() over (partition by ForeignKeyID order by Request) rn
        ,       *
        from @t
        )
select  *
from    numbered n1
order by
        (
        select  Request 
        from    numbered n2 
        where   n2.ForeignKeyID = n1.ForeignKeyID 
                and n2.rn = 1
        )
,       n1.Request

子查询是必需的,因为SQL Server在row_number子句中不允许order by

SE Data的完整示例。