日期:2014-05-19  浏览次数:20420 次

一道很简单的sql语句
有一个表table1
id   name     科目         成绩
1     a         chinese       56
2     b         chinese       45
3     a         english       65
4     b           english     87

我想得到这样的表

name     chinese       english
a             56                 45
b             45                   87
怎么写。

------解决方案--------------------
如果科目固定只有chinese和english的話這樣就可以了

select name, chinese = max(case 科目 when 'chinese ' then 成績 else null end),
english = max(case 科目 when 'engligh ' then 成績 else null end)
from table1
group by name
------解决方案--------------------
declare @s varchar(8000)
select @s = isnull(@s, ' ') + ', max(case 科目 when ' ' ' + 科目 + ' ' ' then 成績 else null end) as [ ' + 科目 + '] '
from table1
set @s = stuff(@s, 1, 1, ' ')
set @s = 'select name, ' + @s + ' from table1 group by name '

exec(@s)

------------
剛才case語句掉了end