如何在 SQL Server 中使用大小写排名

Posted

技术标签:

【中文标题】如何在 SQL Server 中使用大小写排名【英文标题】:how to use rank with case in SQL server 【发布时间】:2014-05-13 06:47:23 【问题描述】:

查询

select 
    territory, new,
    rank() over (order by new ASC) as rank_1  
case 
when rank_1 <= (select count(new)/3 from ##final) then 'low'
when rank_1 <= (select (count(new)/3)*2 from ##final) then 'medium'
when rank_1 <= (select count(new) from ##final) then 'high'
else 'error'
end 
from 
    ##final 
order by 
    territory

表格

territory       new
6310101     941
6310102     186
6310103         458
6310103     458
6310104     109
6310105     113
6310106     305
6310107     189
6310108     184
6310109     737
6310110     862
6310110     862
6310201     1079
6310202     236
6310203     1529

错误信息:

消息 156,第 15 级,状态 1,第 3 行 关键字“case”附近的语法不正确。 消息 156,第 15 级,状态 1,第 4 行 关键字“then”附近的语法不正确。 消息 156,第 15 级,状态 1,第 5 行 关键字“then”附近的语法不正确。 消息 156,第 15 级,状态 1,第 6 行 关键字“then”附近的语法不正确。

【问题讨论】:

【参考方案1】:

不能直接引用此列,需要子查询或CTE:

WITH CTE AS
(
   SELECT territory, new,
        RANK() Over (Order By new ASC) as rank_1  
   FROM ##final 
)
SELECT territory, new, 'error' =
       case 
           when rank_1 <= (select count(new)/3 from ##final) then 'low'
           when rank_1 <= (select count(new)/3 from ##final) then 'medium'
           when rank_1 <= (select count(new)/3 from ##final) then 'high'
       else 'error' end 
FROM CTE
ORDER BY territory

Demo

【讨论】:

以上是关于如何在 SQL Server 中使用大小写排名的主要内容,如果未能解决你的问题,请参考以下文章