日期:2014-05-18  浏览次数:20602 次

关于动态Case When的写法
不知道标题描述有没有歧义。先看我写的SQL:
SQL code

select COUNT(1) c,
(case Professional
when '' then ' '
when '电测' then '电测'
when '电能' then '电能'
when '电能/互感器' then '电能/互感器'
when '高压' then '高压'
when '热工' then '热工'
else '其它' end) as Professional
from device where classfication='mStandard' and ParentID is null group by Professional


得出结果:
SQL code

c   Professional
4   
16  电测   
8   电能
2   电能/互感器
3   高压
14  热工




但是考虑到Professional有可能是动态的,那么上面的写法局限性就很大了,不知能不能动态控制case when?
有个前提是when '' then ' '一定要执行

------解决方案--------------------
给你个动态case when 的实例:
SQL code

create table tb(姓名 varchar(10) , 课程 varchar(10) , 分数 int)
insert into tb values('张三' , '语文' , 74)
insert into tb values('张三' , '数学' , 83)
insert into tb values('张三' , '物理' , 93)
insert into tb values('李四' , '语文' , 74)
insert into tb values('李四' , '数学' , 84)
insert into tb values('李四' , '物理' , 94)
go

declare @sql varchar(8000)
set @sql = 'select 姓名'
select @sql = @sql + ' , max(case 课程 when ''' + 课程+ ''' then 分数 else 0 end) [' + 课程+ ']'
from (select distinct 课程 from tb) as a
set @sql = @sql + ' from tb group by 姓名'
exec(@sql) 
/*
姓名         数学          物理          语文
---------- ----------- ----------- -----------
李四         84          94          74
张三         83          93          74
*/

------解决方案--------------------
建一个表TB。

电测
电能
...


与当前
device
right join TB 

对应值为null的就用‘其它’,

类似这样
SQL code
select COUNT(1) c,
(case when device.Professional is null then '其它'
      when device.Professional='' then ' '
      else TB.Professional end) as Professional 
from device 
right join TB on device.Professional = TB.Professional 
where classfication='mStandard' and ParentID is null group by device.Professional

------解决方案--------------------
declare @sql varchar(8000)
set @sql='select COUNT(1) c'
select @sql=@sql+', max(case Professional when '''+Professional+''' then '''+Professional+''' else 其它 end) ['+ Professional+']'
from (select distinct Professional from device where ParentID is null) as a
set @sql=@sql+' group by Professional'
exec(@sql)