0

我有以下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,那么它不应该显示。

4

1 回答 1

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)    

希望这可以帮助

于 2013-09-20T13:54:50.703 回答