SQLServer2008 关于CASE WHEN

CASE WHEN的两种格式

1.简单Case函数

CASE sex

         WHEN '1' THEN '男'

         WHEN '2' THEN '女'

ELSE '其他' END

2.Case搜索函数

CASE WHEN sex = '1' THEN '男'

         WHEN sex = '2' THEN '女'

ELSE '其他' END

1).两者相比,Case搜索函数功能更强。

2).Case函数类似于if……else if 语句,只返回第一个符合条件的值,之后的部分会被忽略

例子:(按照指定规则分组,并计算每组人数)

create table #temp
(
    country varchar(100),
    people int

)

insert into #temp
select 'A',400 union all
select 'B',2890 union all
select 'C',3490 union all
select 'D',5678 union all
select 'E',457 union all
select 'F',2345


select
CASE WHEN country='A' or country='B' THEN '1组' 
          WHEN country='C' or country='D' THEN '2组'
          WHEN country='E' or country='F'  THEN '3组'
          END 组别,SUM(people) 人数合计
from #temp
group by
CASE WHEN country='A' or country='B' THEN '1组' 
          WHEN country='C' or country='D' THEN '2组'
          WHEN country='E' or country='F'  THEN '3组'
          END

ps.

Order by 后也可使用Case when 用于筛选需要的排序数据

Example:

order by case when ISNULL(A.ReqDate,'')!='' then A.ReqDate else A.PlanReqDate end desc

原文地址:https://www.cnblogs.com/xcxcxcxc/p/5541193.html