CASE中的多个ORDER BY

时间:2011-05-06 08:54:26

标签: sql sql-server sql-server-2005 tsql

我有一个select语句,结尾如下:

order by case @pcsort
            when '' then compcode asc
            else received asc, compcode asc
        end

基本上我需要它,如果@pcsort是'',那么按compcode排序,否则按receivedcompcode按顺序排序。

有什么想法吗?

1 个答案:

答案 0 :(得分:7)

这将做你想要的假设数据类型是兼容的

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