group by,请教有一表数据如下:namesubjectscoretom语文88tom数学97tom英语78abama语文76abama数学92abama
group by,请教
有一表数据如下:
namesubjectscore
tom语文88
tom数学97
tom英语78
abama语文76
abama数学92
abama英语100
如何筛选成如下结果集:
姓名 语文 数学 英语
tom 88 97 78
abama 76 92 100
[解决办法]
- SQL code
--name subject scorewith cte as ( select 'tom' as name,'语文' as [subject],88 as score union all select 'tom','数学',97 union all select 'tom','英语',78 union all select 'abama','语文',76 union all select 'abama','数学',92 union all select 'abama','英语',100 )select name, SUM(case [subject] when '语文' then score else 0 end) as 语文, SUM(case [subject] when '数学' then score else 0 end) as 数学, SUM(case [subject] when '英语' then score else 0 end) as 英语from ctegroup by name/*数据多的话,就用动态脚本 行转列*//*name 语文 数学 英语----- ----------- ----------- -----------abama 76 92 100tom 88 97 78(2 row(s) affected)*/
