SQL ORDER BY有例外

时间:2015-12-18 15:35:22

标签: sql sql-server-2008-r2 sql-order-by rank

我想按3列(Priority,ExpectedDate,CreateDate)排序(子选择的结果)但是对于几行排序应该以不同的方式工作。
用文字描述很难,所以我准备了一张图片:

enter image description here

之前表中的等级

ROW_NUMBER() OVER(ORDER BY Priority DESC, ExpectedDate DESC, CreateDate ASC) AS [Rank],

您可以看到 ShouldBeAfter 列指示 ID ,之后应始终显示此行,无论其类型如何。

如何编写查询以实现之后状态?

编辑1:
样本数据:

DECLARE @Queue TABLE 
(
    [ChildID] INT,
    [ParentID] INT,
    [No] INT,
    [Change] INT,
    [Priority] INT,
    [ExpectedDate] DATETIME,
    [CreateDate] DATETIME
)

INSERT INTO @Queue VALUES (242,   0, 0, 0,  3, '1900-01-01 00:00:00.000', '2015-11-27 15:08:40.677')
INSERT INTO @Queue VALUES (243, 274, 0, 0,  3, '1900-01-01 00:00:00.000', '2015-11-27 15:22:46.350')
INSERT INTO @Queue VALUES (244,   0, 0, 0,  3, '1900-01-01 00:00:00.000', '2015-11-27 15:29:52.010')
INSERT INTO @Queue VALUES (259,   0, 0, 0,  3, '1900-01-01 00:00:00.000', '2015-11-30 15:54:48.710')
INSERT INTO @Queue VALUES (261,   0, 0, 0,  4, '1900-01-01 00:00:00.000', '2015-12-01 11:07:32.357')
INSERT INTO @Queue VALUES (263,   0, 0, 0,  5, '1900-01-01 00:00:00.000', '2015-12-02 12:07:01.980')
INSERT INTO @Queue VALUES (264,   0, 0, 0,  2, '1900-01-01 00:00:00.000', '2015-12-03 14:58:19.717')
INSERT INTO @Queue VALUES (266,   0, 0, 0,  3, '1900-01-01 00:00:00.000', '2015-12-08 09:55:06.277')
INSERT INTO @Queue VALUES (269,   0, 0, 0,  3, '2015-12-16 00:00:00.000', '2015-12-08 17:53:24.820')
INSERT INTO @Queue VALUES (270,   0, 0, 0,  3, '1900-01-01 00:00:00.000', '2015-12-09 15:50:37.970')
INSERT INTO @Queue VALUES (272,   0, 0, 0,  3, '1900-01-01 00:00:00.000', '2015-12-11 12:06:19.253')
INSERT INTO @Queue VALUES (273, 242, 0, 0,  3, '1900-01-01 00:00:00.000', '2015-12-11 12:08:20.010')
INSERT INTO @Queue VALUES (274,   0, 0, 0,  2, '1900-01-01 00:00:00.000', '2015-12-11 12:09:00.200')
INSERT INTO @Queue VALUES (275,   0, 0, 0,  3, '1900-01-01 00:00:00.000', '2015-12-11 12:14:50.110')
INSERT INTO @Queue VALUES (276,   0, 0, 0,  3, '1900-01-01 00:00:00.000', '2015-12-11 12:17:49.220')
INSERT INTO @Queue VALUES (277,   0, 0, 0,  3, '1900-01-01 00:00:00.000', '2015-12-11 12:24:28.823')
INSERT INTO @Queue VALUES (278,   0, 0, 0,  5, '2015-12-10 00:00:00.000', '2015-12-11 12:27:53.803')
INSERT INTO @Queue VALUES (279,   0, 0, 0,  3, '1900-01-01 00:00:00.000', '2015-12-11 12:32:14.397')
INSERT INTO @Queue VALUES (280,   0, 0, 0,  2, '1900-01-01 00:00:00.000', '2015-12-11 13:56:06.080')
INSERT INTO @Queue VALUES (281,   0, 0, 0,  2, '1900-01-01 00:00:00.000', '2015-12-15 10:16:35.057')
INSERT INTO @Queue VALUES (282, 276, 0, 0,  3, '1900-01-01 00:00:00.000', '2015-12-15 10:18:50.180')
INSERT INTO @Queue VALUES (284,   0, 0, 0,  3, '1900-01-01 00:00:00.000', '2015-12-15 11:33:33.553')

1 个答案:

答案 0 :(得分:0)

这有点痛苦,因为你需要额外的加入:

select t.*
from t left join
     t2
     on t.id = t2.shouldbeafter
order by coalesce(t2.shouldbeafter, t.id),
         t.shouldbeafter, t.id;

注意:这适用于一个级别,但不适用于多个级别。