Order a column conditional in SQL

来源:互联网 发布:陈建仁访问梵蒂冈'知乎 编辑:程序博客网 时间:2024/05/10 08:47

The below sample illustrates that we order Z descending if Zone is an even number, order Z ascending if Zone is an odd number.

 

declare @WhLocation table
(
      LocationId int identity(1, 1),
      Zone int,
      Z varchar(20)
)
insert into @WhLocation values
                              (1, '2'),
                              (1, '3'),
                              (1, '1'),
                              (2, '1'),
                              (2, '3'),
                              (2, '2')
SELECT * FROM @WhLocation
ORDER BY
CASE WHEN Zone IS NOT NULL AND Zone%2=1 --odd number
    THEN Z END ASC,
CASE WHEN (1=1)
    THEN Z END DESC --NULL OR even number

原创粉丝点击