日期:2014-05-18 浏览次数:20820 次
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
c Professional 4 16 电测 8 电能 2 电能/互感器 3 高压 14 热工
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的就用‘其它’,
类似这样
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)