--查询分数段的结果得到这个表结构
单位 分段 人数
学校一 1-->10 657
学校二 1-->10 179
学校一 1-->20 366
学校二 1-->20 295
学校一 1-->30 657
学校二 1-->30 179
学校一 1-->40 366
学校二 1-->40 295--需要转换成这样的表结构
--主要是这里分数段是动态的.有可能更多分段,
单位 1-->10 1-->20 1-->30 1-->40
学校一 657 366 657 366
学校二 179 295 179 295 望指教
sum(case 分段 when '1-->10' then 人数 else 0 end) [1-->10],
sum(case 分段 when '1-->20' then 人数 else 0 end) [1-->20],
sum(case 分段 when '1-->30' then 人数 else 0 end) [1-->30],
sum(case 分段 when '1-->40' then 人数 else 0 end) [1-->40]
from tb group by 单位
if object_id('tempdb.dbo.#tb') is not null drop table #tb
go
create table #tb (单位 varchar(6),分段 varchar(6),人数 int)
insert into #tb
select '学校一','1-->10',657 union all
select '学校二','1-->10',179 union all
select '学校一','1-->20',366 union all
select '学校二','1-->20',295 union all
select '学校一','1-->30',657 union all
select '学校二','1-->30',179 union all
select '学校一','1-->40',366 union all
select '学校二','1-->40',295select 单位,
[1-->10]=MAX(case when 分段='1-->10' then 人数 else 0 end ),
[1-->20]=MAX(case when 分段='1-->20' then 人数 else 0 end ),
[1-->30]=MAX(case when 分段='1-->30' then 人数 else 0 end ),
[1-->40]=MAX(case when 分段='1-->40' then 人数 else 0 end )
from #tb
group by 单位
单位 1-->10 1-->20 1-->30 1-->40
------ ----------- ----------- ----------- -----------
学校二 179 295 179 295
学校一 657 366 657 366(2 row(s) affected)
create table #tb (单位 varchar(6),分段 varchar(6),人数 int)
insert into #tb
select '学校一','1-->10',657 union all
select '学校二','1-->10',179 union all
select '学校一','1-->20',366 union all
select '学校二','1-->20',295 union all
select '学校一','1-->30',657 union all
select '学校二','1-->30',179 union all
select '学校一','1-->40',366 union all
select '学校二','1-->40',295
godeclare @sql varchar(max)
set @sql = 'select 单位'
select @sql = @sql + ',max(case 分段 when ''' + 分段 + ''' then 人数 else 0 end)[' + 分段 + ']'
from(select distinct 分段 from #tb)u
select @sql = @sql + ' from #tb group by 单位'
exec(@sql)drop table #tb
单位 1-->10 1-->20 1-->30 1-->40
------ ----------- ----------- ----------- -----------
学校二 179 295 179 295
学校一 657 366 657 366(2 行受影响)