展开全部
最简捷直观的方法就是利用分组
select ID,
Sum(语文) 语文,
Sum(数学) 数学,
Sum(英语) 英语
from scores
group by ID
你可以直接用下面的语句在SQL Server中测试结果:
DECLARE @ScoresVar table(
ID int NOT NULL,
Chinese int,
Math int,
English int);
Insert into @ScoresVar
values(1 ,70, null, null)
Insert into @ScoresVar
values(1 ,null,80, null)
Insert into @ScoresVar
values(1 ,null, null, 90)
Insert into @ScoresVar
values(2 ,75, null, null)
Insert into @ScoresVar
values(2 ,null,85, null)
Insert into @ScoresVar
values(2 ,null, null, 95)
select ID,
SUM(Chinese) Chinese,
Sum(Math) Math,
Sum(English) English
from @ScoresVar
group by ID
还有一种方法,可能更通用一点,利用 FOR XML PATH 和STUFF函数来做,虽然复杂,但是对表的数据类型无限制。
还是上面的测试数据,你可以通过下面的代码来得到你想要的数据:
SELECT ID,
STUFF((SELECT ',' + Cast(A.Chinese as varchar)
FROM @ScoresVar A Where A.ID=B.ID FOR XML PATH('')),1,1,'') As Chinese,
STUFF((SELECT ',' + Cast(A.Math as varchar)
FROM @ScoresVar A Where A.ID=B.ID FOR XML PATH('')),1,1,'') As Math,
STUFF((SELECT ',' + Cast(A.English as varchar)
FROM @ScoresVar A Where A.ID=B.ID FOR XML PATH('')),1,1,'') As English
From @ScoresVar B
Group By ID
-- 输出结果
ID Chinese Math English
1 70 80 90
2 75 85 95
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询