34,587
社区成员
发帖
与我相关
我的任务
分享
select
学校,
sum(case 班级 when '一年级' then 1 else 0 end) as 人数,
sum(case 班级 when '一年级' then 费用 else 0 end) as 费用,
sum(case 班级 when '二年级' then 1 else 0 end) as 人数,
sum(case 班级 when '二年级' then 费用 else 0 end) as 费用
from
tb
group by
学校
create table tb(学校 varchar(10),班级 varchar(10),学生 varchar(2),费用 int)
insert into tb
select '一中','一年级','A',9 union all
select '一中','一年级','B',9 union all
select '一中','一年级','C',9 union all
select '一中','二年级','D',9 union all
select '二中','一年级','E',9 union all
select '二中','一年级','F',9 union all
select '三中','二年级','G',9 union all
select '三中','二年级','H',10
DECLARE @sql NVARCHAR(2000)
set @sql='select 学校'
select @sql=@sql+',sum(case 班级 when'''+班级+''' then 1 else 0 end) ['+班级+'人数],'+
'sum(case 班级 when'''+班级+''' then 费用 else 0 end) ['+班级+'费用]'
from tb group by 班级
SET @sql=@sql+' from tb group by 学校'
EXEC(@sql)
/*
学校 二年级人数 二年级费用 一年级人数 一年级费用
---------- ----------- ----------- ----------- -----------
二中 0 0 2 18
三中 2 19 0 0
一中 1 9 3 27
(3 行受影响)