如何根据SQL Server中列的值来对select语句的数据集进行排序

时间:2017-08-22 09:55:34

标签: sql sql-server

我有这张桌子

create table Item
(
    Id bigint primary key identity(1,1),
    Status nvarchar(100),
    DateFiled datetime
)

INSERT INTO Item 
VALUES ('CLOSED', '2017-08-23 16:42:32.720'), --1
       ('OPEN', '2017-08-21 16:42:32.720'), --2
       ('OPEN', '2017-08-22 16:42:32.720'), --3
       ('GRABBED', '2017-08-22 16:42:32.720'), --4
       ('CLOSED', '2017-08-21 16:42:32.720'), --5
       ('OPEN', '2017-08-23 16:42:32.720'); --6

如何按以下条件排序单个select语句?

  • 如果(没有标记的项目):1个最早提交的OPEN状态的记录项应该是第一行。
  • ELSE:GRABBED项目应该是第一个

  • 关闭已关闭的项目

  • 其余的未清项目

2 个答案:

答案 0 :(得分:2)

您可以使用子查询计算一些摘要统计信息,然后在order by中使用它。

如果我的规则是正确的:

select i.*
from (select i.*,
             row_number() over (partition by status order by datefiled) as seqnum,
             sum(case when status = 'GRABBED' then 1 else 0 end) over () as num_grabbed
      from items i
     ) i
order by (case when num_grabbed = 1 and status = 'OPEN' and seqnum = 1
            then 1
            when status = 'GRABBED' then 2
            when status = 'CLOSED' then 3
            else 4
       end);

答案 1 :(得分:1)

您可以使用案例创建条件order by。它将按每行的大小写结果排序。

order by case when exists (select 1 from Item where status = 'GRABBED')
                  then case
                          when status = 'GRABBED' then 1
                          when status = 'CLOSED' then 2
                          when status = 'OPEN' then 3
                          else 4
                      end       
                  else case
                           when status = 'OPEN' then 1
                           else 2
                       end
              end, 
         DateFiled