摘要:
下文通过详解的方式分析case when 的用法
涉及统计、分类、排序
一、case when then 用法简介
case when then 用法1:
case [字段]
when '字段等于相应的value' then 表达式
when '字段等于相应的value' then 表达式
else ''
end
———————————————————-
case when then 用法2:
case
when [条件] then 表达式
when [条件] then 表达式
else ''
end
二、case when then 用法举例说明
---下文举例分析了case when常用的用法,如下所示:涉及排序字段的应用
create table test
(
qty int ,
sort varchar(20)
)
insert into test(qty,sort)values
(1,'a'),(2,'b'),(3,'d'),(1,'e')
go
----方法1:
select sort,qty,
case qty
when 1 then '少'
when 2 then '中'
when 3 then '多'
else '未知'
end as [数量范围]
from test
--方法2:
select sort,qty,
case
when qty=1 then '少'
when qty=2 then '中'
when qty=3 then '多'
else '未知'
end as [数量范围]
from test
---sum统计用法
select
sum( case when qty=1 then 1 else 0 end) as [少],
sum( case qty when 2 then 1 else 0 end) as [中],
sum( case when qty=3 then 1 else 0 end) as [多],
sum( case when qty<> 1 and qty <>2 and qty <>3 then 1 else 0 end) as [位置]
from test
---case when 做排序字段
declare @i int
set @i=0
select * from test
order by
case @i when 0 then qty else sort end
go
truncate table test
drop table test