SQL Server条件Order By具有多个列

时间:2018-02-08 17:31:09

标签: sql sql-server tsql

我有一个包含数千个执行的表,这些执行可能在州列中具有以下结果之一:

OK
NOTOK
CANCELED
RUNNING

我需要一个查询,我可以对结果进行排序,以便运行的执行显示在顶部,其余结果按开始日期或ID排序,根据用户的喜好。

例如: 表记录:

ID - STATE - START_DATE
1      OK      12:00
2    RUNNING   12:10
3     NOTOK    12:30
4    RUNNING   12:45
5      OK      13:00

按START_DATE排序时预期结果:

ID - STATE - START_DATE
4   RUNNING    12:45
2   RUNNING    12:10
5     OK       13:00
3    NOTOK     12:30
1     OK       12:00

这是我已经拥有的查询(简化):

SELECT TOP (@ITEMS_PAGE) ID, START_DATE, STATE
FROM 
    (SELECT ROW_NUMBER() OVER (ORDER BY
                                  CASE WHEN @ORDER = 'ID&ASC' THEN ID END ASC,
                                  CASE WHEN @ORDER = 'ID&DESC' THEN ID  END DESC,
                                  CASE WHEN @ORDER = 'START_DATE&ASC' THEN START_DATE END ASC,
                                  CASE WHEN @ORDER = 'START_DATE&DESC' THEN START_DATE END DESC,
                                  CASE WHEN @ORDER = 'STATE&ASC' THEN STATE END ASC,
                                  CASE WHEN @ORDER = 'STATE&DESC' THEN STATE END DESC,
                                  CASE WHEN @ORDER IS NULL THEN ID END DESC
                              ) AS ROWNUMBERS, * 
     FROM @TMPPAGING 
     WHERE (@RESULT is null or STATE = @RESULT)
) S
WHERE S.ROWNUMBERS > (@CURRENT_PAGE - 1) * @ITEMS_PAGE

@TMPPAGING包含记录。

1 个答案:

答案 0 :(得分:1)

你正在使它变得比它需要的复杂得多。这是您通过start_date订购的SQL:

with inputdata as ( select 1 as id, 'OK' as state, convert(datetime, '2018-01-10 12:00') as start_date
union all select 2 as id, 'RUNNING' as state, convert(datetime, '2018-01-10 12:10') as start_date
union all select 3 as id, 'NOTOK' as state, convert(datetime, '2018-01-10 12:30') as start_date
union all select 2 as id, 'RUNNING' as state, convert(datetime, '2018-01-10 12:45') as start_date
union all select 2 as id, 'OK' as state, convert(datetime, '2018-01-10 13:00') as start_date

) 
select * from inputdata order by case when state='RUNNING' then 1 else 2 end, start_date

这导致:

id  state   start_date
2   RUNNING 2018-01-10 12:10:00.000
2   RUNNING 2018-01-10 12:45:00.000
1   OK      2018-01-10 12:00:00.000
3   NOTOK   2018-01-10 12:30:00.000
2   OK      2018-01-10 13:00:00.000