sql - CASE 内的多个 ORDER BY

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

我有一个 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/

相关文章:

sql - 如何从不包含撇号的搜索字符串中返回包含撇号的查询结果

sql-server - SQL几何多边形的方向并跨越国际日期线(IDL)

c# - 无法使用 asp.net web 应用程序将数据插入 SQL Server 数据库

sql - 如何查找连续缺勤n天的人?

sql-server - Sql Server 2005如何更改dbo登录名

database - 是否可以在当前数据库以外的数据库上查询@@DBTS?

mysql - 哪些点使sql查询更快

c# - Entity Framework 对导航属性的约束

sql - 如何旋转这个父子表?

sql - 索引 : Avoid duplicates in table when Status = 'S'