我们用到的表结构如下:
三张表的关系为:
现有的测试数据为:
我们需要的结果是:
代码如下:
DECLARE @strsql VARCHAR(8000)
SET @strsql = 'SELECT t.STUNAME [姓名]'
SELECT @strsql = @strsql + ',SUM(CASE s.SNAME WHEN ''' + SNAME + ''' THEN g.[score] END) [' + SNAME + ']' FROM (SELECT SNAME FROM [Subject]) AS tmp
SELECT @strsql = @strsql + ' FROM [score] g,[Subject] s,[Student] t WHERE g.SID=s.SID AND g.STUID = t.STUID GROUP BY t.STUID,t.STUNAME'
EXEC(@strsql)
SET @strsql = 'SELECT t.STUNAME [姓名]'
SELECT @strsql = @strsql + ',SUM(CASE s.SNAME WHEN ''' + SNAME + ''' THEN g.[score] END) [' + SNAME + ']' FROM (SELECT SNAME FROM [Subject]) AS tmp
SELECT @strsql = @strsql + ' FROM [score] g,[Subject] s,[Student] t WHERE g.SID=s.SID AND g.STUID = t.STUID GROUP BY t.STUID,t.STUNAME'
EXEC(@strsql)
sql SERVER 2005 中,已经有实现此功能的内置方法了。