开发者

Multiple ORDER BY within CASE

开发者 https://www.devze.com 2023-03-03 22:05 出处:网络
I have a select statement which ends in the following: order by case @pcsort w开发者_高级运维hen \'\' then compcode asc

I have a select statement which ends in the following:

order by case @pcsort
            w开发者_高级运维hen '' then compcode asc
            else received asc, compcode asc
        end

Basically I need it if @pcsort is ' ' then order by compcode, otherwise order by received and compcode in that order.

Any ideas?


This will do what you want assuming datatypes are compatible

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

More generally, you need one CASE per sort column assuming datatypes are compatible

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

Where datatypes are incompatible, you need more cases and a lot of constants

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
0

精彩评论

暂无评论...
验证码 换一张
取 消