我有一个 select 语句,其结尾如下:
order by case @pcsort
when '' then compcode asc
else received asc, compcode asc
end
基本上我需要它,如果 @pcsort
是 ' ' 则按 compcode
排序,否则按 received
排序和compcode
按此顺序。
有什么想法吗?
最佳答案
这将实现您想要的假设数据类型兼容
order by
case @pcsort
when '' then compcode
else received
end ASC,
compcode ASC
更一般地说,假设数据类型兼容,每个排序列需要一个 CASE
order by
case @pcsort
when '' then compcode
else received
end ASC,
case @pcsort
--safe to sort on same column agaon , or use a constant
when '' then compcode or <constant of same type as compcode>
else compcode
end ASC
当数据类型不兼容时,您需要更多的情况和大量的常量
order by
case @pcsort
when '' then compcode
else <constant of same type as compcode>
end ASC,
case @pcsort
when '' then <constant of same type as received>
else received
end ASC,
case @pcsort
when '' then <constant of same type as compcode>
else compcode
end ASC
关于sql - CASE 内的多个 ORDER BY,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5909034/