【问题标题】:How to maintain the order of one column after changing it in the SELECT expression在 SELECT 表达式中更改一列后如何保持其顺序
【发布时间】:2021-11-24 13:36:36
【问题描述】:

当我按CreditRating 订购时,它是按照描述的顺序,所以“高于平均水平”排在第一位。我要下单

  1. 高级
  2. 优秀
  3. 高于平均水平
select VendorID as FournisseurID,
        V.Name as NomFournisseur, 
        CreditRating = 
        case
            when CreditRating = '1' then 'Superior' 
            when CreditRating = '2' then 'Excellent' 
            when CreditRating = '3' then 'Above average' 
            when CreditRating = '4' then 'Average' 
            when CreditRating = '5' then 'Below average'
        end,             
        sum(TotalDue) as TotalDû
from Purchasing.ProductVendor PV
Order by CreditRating, V.Name

【问题讨论】:

  • 如果CreditRatingint 数据类型,那么您不应该使用'' 来比较数字

标签: sql sql-server sql-order-by


【解决方案1】:

只需为您的 CASE 表达式使用不同的名称,然后使用原始列执行 ORDER BY

select V.VendorID as FournisseurID,
        V.Name as NomFournisseur, 
        case
            when V.CreditRating = '1' then 'Superior' 
            when V.CreditRating = '2' then 'Excellent' 
            when V.CreditRating = '3' then 'Above average' 
            when V.CreditRating = '4' then 'Average' 
            when V.CreditRating = '5' then 'Below average'
        end as CreditRatingText,             
        sum(V.TotalDue) as TotalDû
from Purchasing.ProductVendor V
order by V.CreditRating, V.Name

【讨论】:

    【解决方案2】:

    ORDER BY 具有复杂的绑定规则。

    如果您指定的列具有 no 表引用,它将first 绑定到来自SELECT 的匹配列,而不是@987654324 中的列@。 如果没有找到匹配项,则使用FROM 中的列。

    而如果您指定表引用,FROM 中的原始列将始终使用。

    See this fiddle for the difference.

    因此,作为一项规则,如果您真的需要具有相同的名称(为了混淆,您应该避免使用),如果您想要原始列的排序,请指定表引用

    select VendorID as FournisseurID,
           V.Name as NomFournisseur, 
           CreditRating = 
            case CreditRating 
                when '1' then 'Superior' 
                when '2' then 'Excellent' 
                when '3' then 'Above average' 
                when '4' then 'Average' 
                when '5' then 'Below average'
            end,             
           sum(TotalDue) as TotalDû
    from Purchasing.ProductVendor PV
    GROUP BY PV.CreditRating, PV.Name, PV.VendorID
    Order by PV.CreditRating, PV.Name
    

    【讨论】:

      猜你喜欢
      • 2021-02-15
      • 1970-01-01
      • 2021-06-09
      • 2022-12-24
      • 1970-01-01
      • 1970-01-01
      • 2022-12-16
      • 1970-01-01
      • 2018-11-01
      相关资源
      最近更新 更多