SQL按分组排序

4
我有以下查询。
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 应该相邻出现,但没有。

你不能只是在你的order by语句末尾添加foreignKeyId吗? - DarylChymko
每当ForeignKeyId有重复时,可以假定Request将为NULL吗? - Michael Ames
1个回答

2
你可以通过ForeignKeyId进行分区,然后将第二行或更低行按其“头”排序。其中,“头”被定义为该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不允许在order by子句中使用row_number

完整示例请参见SE Data


在你编辑回答之前,我已经编辑了我的问题。我会看一下这个的。 - PMC
这个可以用,谢谢。希望它更简单一些,因为要去到DevExpress网格进行自定义排序,但是没关系。 - PMC

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接