You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SELECT表达式中修改列后,保持该列的自定义排序顺序

解决方法

你当前排序不符合预期的核心原因是:ORDER BY子句引用的CreditRating是SELECT语句中经过CASE转换后的字符串别名,数据库会按照字符串的字典序排序,首字母A开头的Above average自然会排在S开头的Superior前面。

你需要的排序规则和原始CreditRating字段的1、2、3、4、5的数值顺序完全匹配,直接在排序时指定用原始表的未转换字段即可,注意要加表别名PV.避免和转换后的别名冲突:

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 PV.CreditRating, V.Name

如果你的场景不允许直接用原始字段排序,也可以在ORDER BY里手动指定排序权重:

Order by 
    case CreditRating
        when '1' then 1
        when '2' then 2
        when '3' then 3
        when '4' then 4
        when '5' then 5
    end, 
    V.Name

内容的提问来源于stack exchange,提问作者Jessica Lamoureux

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 08:45:07