生成值存在的列

时间:2013-09-20 10:53:12

标签: sql group-by dynamically-generated

我有以下sql:

select ks2en, 
   count(case result when 'C-' then 1 end) as 'C-',
   count(case result when 'C' then 1 end) as 'C',
   count(case result when 'C+' then 1 end) as 'C+',
   count(case result when 'B' then 1 end) as 'B',
   count(case result when 'A' then 1 end) as 'A'
from student join subject 
on subject.upn=student.upn 
where name='English'
group by ks2en;

生成以下结果:

ks2en   C-  C   C+  B   A
        0   3   0   0   0
2a      0   0   0   0   0
3a      18  0   0   0   0
3b      0   0   0   0   0
3c      0   0   0   0   0
4a      3   11  1   1   0
4b      3   3   36  0   0
4c      1   26  0   0   0
5b      0   3   0   1   0
5c      3   12  4   33  0

但是,我想生成列,以便列中没有总计,即列A,则不应显示。

1 个答案:

答案 0 :(得分:0)

首先,您可能希望遵循juergen的建议来处理业务层中的这种情况,但如果您坚持逻辑在DB级别下面是需要思考的事情。

-- just some sample to work with
create table #student (upn int)
  insert into #student select 1 union all select 2

create table #subject (upn int, result varchar(3))
  insert into #subject select 1, 'C-' union all select 1, 'B' union all select 2, 'A'

--first get the Set of unique [result]s
declare @sqlStr varchar(max)

select @sqlStr = '['+ 
replace(
    stuff((select distinct ','+result as [text()]
    from #subject s
        for xml path ('')) ,1,1,'')
        ,',','],[') + ']' 
from #subject s1

select @sqlStr

--assemble dynamic query
declare @sqlStr1 varchar(max)
set @sqlStr1 = 'select *
    from 
(select #subject.*
from #student 
join #subject on #subject.upn=#student.upn) a
pivot (count (result) for result in ('+@sqlStr+')
        ) p'
-- run dynamic query
 exec (@sqlStr1)    

希望这会有所帮助