Order a column conditional in SQL

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

你可能感兴趣的:(insert,table,null,sql,数据库)