create table 学生表(院系名称 varchar(20),专业编号 char(4),学号 char(8),姓名 varchar(20))
insert 学生表(院系名称,专业编号,学号,姓名)
select '中文学院','0101','00140001','李成' union all
select '管理学院','0201','00140002','白智诚' union all
select '中文学院','0201','00140000','白智诚1' union all
select '管理学院','0203','00140008','秦成' union all
select '管理学院','0201','00140009','秦成1' union all
select '管理学院','0201','00140010','秦成2' union all
select '中文学院','0102','00140003','梁涛' union all
select '中文学院','0101','00140004','廖志国'
--select * from 学生表create table 学生类别(专业编号 char(4),类别 varchar(20) ) 
insert 学生类别(专业编号,类别)
select '0101','师范' union all
select '0102','非师范' union all
select '0201','师范' union all
select '0203','非师范'
--select * from 学生类别create table 银行数据(学号 char(8),姓名 varchar(20),学费 int,住宿费 int)
insert 银行数据(学号,姓名,学费,住宿费)
select '00140001','李成','3000','700' union all
select '00140008','秦成','0','600' union all
select '00140009','秦成2','4000','700' union all   -- 加多的测试数据
select '00140010','秦成3','3000','800' union all   -- 加多的测试数据
select '00140002','白智诚','3000','800' union all
select '00140000','白智诚1','3000','800' union all -- 加多的测试数据
select '00140003','梁涛','2500','0'
--select * from 银行数据
/*
select * from 银行数据 Y
left join 学生表 S on 
Y.学号=S.学号 left join 学生类别 T on 
S.专业编号=T.专业编号
*/
select 院系名称,类别,sum(学费) as 学费,count(院系名称) as 人数,
sum(住宿费1) as 住宿费1,sum(住宿费1人数) as 住宿费1人数,sum(住宿费2) as 住宿费2,sum(住宿费2人数) as 住宿费2人数
into test from 
(
select S.院系名称,T.类别,Y.学费,
case Y.住宿费 when 800 then Y.住宿费 else 0 end as 住宿费1,
case Y.住宿费 when 800 then 1 else 0 end as 住宿费1人数,
case Y.住宿费 when 800 then 0 else Y.住宿费 end as 住宿费2,
case Y.住宿费 when 800 then 0 else 1 end as 住宿费2人数
from 银行数据 Y
left join 学生表 S on 
Y.学号=S.学号 left join 学生类别 T on 
S.专业编号=T.专业编号
)A
group by 院系名称,类别
order by 院系名称
select * from test--院系 师范学费  人数 非师范学费  人数  住宿费1  人数 住宿费2 人数--用于:交叉表的列数是不确定的
declare @sql varchar(8000)set @sql = 'select 院系名称,'+'sum(住宿费1) as 住宿费1,' +
'sum(住宿费1人数) as 住宿费1人数,' +
'sum(住宿费2) as 住宿费2,' +
'sum(住宿费2人数) as 住宿费2人数,' select @sql = @sql + 'sum(case 类别 when '''+类别+''' 
                          then 学费 else 0 end) as '''+类别 + '学费'+''',' +
'sum(case 类别 when '''+类别+''' 
                          then 人数 else 0 end) as '''+类别 + '学费人数'+''',' from (select distinct 类别 from test) as a 
select @sql = left(@sql,len(@sql)-1) + ' from test group by 院系名称'
exec(@sql)
godrop table test /*删除数据表*/
drop table 学生表,学生类别,银行数据 /*删除数据表*/
go结果1
院系名   类别     学费    人数     住宿费1   人数     住宿费2  人数  
管理学院 非师范 0 1 0 0 600 1
管理学院 师范 10000 3 1600 2 700 1
中文学院 非师范 2500 1 0 0 0 1
中文学院 师范 6000 2 800 1 700 1
问题1:怎么解决管理学院非师范学费为0人数应为0,中文学院非师范住宿费2为0人数应为0问题?
结果2
院系名称住宿费1   人数     住宿费2  人数     师范学费 人数   非师范学费 人数
管理学院 1600 2 1300 2 0 1 10000 3
中文学院 800 1 700 2 2500 1 6000 2
要解决问题2:把住宿费1   人数     住宿费2  人数4个字段移到后面.
请帮忙修改一下代码.