具有条件和多个排序列的case by case语句

时间:2017-07-17 12:34:39

标签: sql sql-order-by

我希望能够根据选择的参数使用不同的列进行排序。 我可以让它为单列工作,但正在努力与多个。 任何帮助将不胜感激。

ORDER BY
CASE WHEN @a like '%apples%' or @a like '%onions%' then
DeliveryScheduleItems.DropSequence, 
DeliveryAddresses.PostalCode,
Customers.CustomerId
Else
DeliverySchedules.DeliveryDate,
DeliveryAddresses.PostalCode,
Customers.CustomerId
End

2 个答案:

答案 0 :(得分:0)

试试这个,

ORDER BY
CASE 
WHEN @a like '%apples%' or @a like '%onions%' then
DeliveryScheduleItems.DropSequence, 
DeliveryAddresses.PostalCode,
Customers.CustomerId
WHEN @a not like '%apples%' AND @a not like '%onions%' then
DeliverySchedules.DeliveryDate,
DeliveryAddresses.PostalCode,
Customers.CustomerId
End

答案 1 :(得分:0)

您需要多个条件:

ORDER BY (CASE WHEN @a like '%apples%' or @a like '%onions%'
               THEN DeliveryScheduleItems.DropSequence
          END),
         (CASE WHEN @a like '%apples%' or @a like '%onions%'
               THEN NULL
               ELSE DeliverySchedules.DeliveryDate
          END),
         DeliveryAddresses.PostalCode,
         Customers.CustomerId

请注意两个不同列使用两个CASE表达式。据推测,DeliveryDateDropSequence有不同的类型。最好单独订购。