我有以下查询

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应该彼此相邻出现,但不要

最佳答案

您可以通过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中的完整示例。

08-03 13:51