交叉表查询
1.动态列
declare @s varchar(8000)
set @s='select 姓名'
select @s=@s+',['+科目+']=max(case 科目 when '''+科目+''' then 成绩 else null end)' from (select distinct 科目 from 科目表) as a
exec(@s+' from 成绩表 group by 姓名')
2.固定列
SELECT 姓名,
max(case a.科目 when '数学' then 成绩 else '' end)as 数学,
max(case a.科目 when '语文' then 成绩 else '' end) as 语文,
max(case a.科目 when '化学' then convert(int,成绩) else '' end) as 化学
from 成绩表
group by 姓名
浙公网安备 33010602011771号