SQL 语句 如何把多行数据放入一行显示 比如:
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQL 语句 如何把多行数据放入一行显示 比如:相关的知识,希望对你有一定的参考价值。
SID FID MID Score
----------- ---------- ---------- -----------
1 1 T001 80
2 2 T001 72
3 3 T001 68
4 4 T001 88
5 1 T002 65
6 2 T002 98
7 3 T002 78
8 4 T002 72
9 1 T003 66
10 2 T003 76
如何得到
T001 80 72 68 88
T002 68 98 78 72
......
if exists(select * from sysobjects where name='Fgetscore' and xtype='FN')
begin
drop function Fgetscore
end
go
create function Fgetscore(@mid as nvarchar(20))
returns nvarchar(2000)
as
begin
declare @sscore nvarchar(2000)
declare @nscore as float
declare cur1 cursor for
select score from tablename where mid=@mid
set @sscore=@mid
open cur1
fetch next from cur1 into @nscore
while @@fetch_status=0 --循环取出score
begin
set @sscore=@sscore + ' ' + cast(@nscore as nvarchar(10))
fetch next from cur1 into @nscore
end
return @sscore
end
go
创建好函数后,像如下调用就可以了(切记“dbo.”不能省略):
select dbo.Fgetscore(mid) as scores from tablename group by mid 参考技术A 如果FID是固定的只有1,2,3,4,可以用下面的sql实现
select MID,
sum(case when fid = 1 then score else null end) score1,
sum(case when fid = 2 then score else null end) score2,
sum(case when fid = 3 then score else null end) score3,
sum(case when fid = 4 then score else null end) score4
from tablename
group by MID本回答被提问者采纳 参考技术B select A.MID,MAX(A.FID1),MAX(A.FID2),MAX(A.FID3),MAX(A.FID4)
(SELECT MID,(case when FID=1 THEN Score else -1 end) as FID1
,(case when FID=2 THEN Score else -1 end) as FID2
,(case when FID=3 THEN Score else -1 end) as FID3
,(case when FID=4 THEN Score else -1 end) as FID4
FROM TableName
) A
GROUP BY A.MID 参考技术C select
decode(mid,'T001',score),
decode(mid,'T002',score)
from yourtablename;
SQL多行合并为一行,SQL语句如何写
把这样的数据
合并为这样的
通过相同的ID
最简捷直观的方法就是利用分组
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 参考技术A select id,max(语文) 语文,max(数学) 数学,max(英语) 英语
from tab
group by id
以上是关于SQL 语句 如何把多行数据放入一行显示 比如:的主要内容,如果未能解决你的问题,请参考以下文章