在 SQL 服务器中串联多行和多列
Concatenation multiple rows and columns in SQL Server
我有以下 table。
Student
table:
Id Name
1 A
2 B
Marks
table:
StudentId SubjectId Marks
1 1 67
1 2 89
2 1 78
2 2 86
我想为给定的 studentId 和 SubjectId 连接多行,将列标记为单个列,如下所示。
结果:
Id Name SubjectMarks
1 A 1:67,2:89
2 B 1:78,2:86
我试过了FOR XML PATH
。它适用于单列,但对于 2 列我无法编写查询。
MS SQL Server 2008 架构设置:
CREATE TABLE Student (Id INT, Name VARCHAR(10))
INSERT INTO Student VALUES
(1 ,'A'),
(2 ,'B')
CREATE TABLE Marks (StudentId INT , SubjectId INT , Marks INT)
INSERT INTO Marks VALUES
(1 , 1 , 67),
(1 , 2 , 89),
(2 , 1 , 78),
(2 , 2 , 86)
查询 1:
;WITH cte AS
(
SELECT StudentId
, CAST(SubjectId AS VARCHAR(10)) + ':'
+ CAST(Marks AS VARCHAR(10)) AS SubjectMarks
FROM Marks
)
SELECT DISTINCT
S.Id
,S.Name
,STUFF((SELECT ',' + SubjectMarks
FROM cte
WHERE x.StudentId = StudentId
FOR XML PATH(''),TYPE)
.value('.','Varchar(max)'),1,1,'') AS SubjectMarks
FROM cte x
INNER JOIN Student S ON S.Id = x.StudentId
| Id | Name | SubjectMarks |
|----|------|--------------|
| 1 | A | 1:67,2:89 |
| 2 | B | 1:78,2:86 |
你可以在没有 CTE 的情况下做到这一点:
select s.id, s.name,
stuff((select ',' + cast(subjectid as varchar(8000)) + ':' + cast(marks as varchar(8000))
from marks m
where m.studentid = s.id
for xml path (''), type
).value('.', 'varchar(max)'), 1, 1, ''
) as SubjectMarks
from student s;
我有以下 table。
Student
table:
Id Name
1 A
2 B
Marks
table:
StudentId SubjectId Marks
1 1 67
1 2 89
2 1 78
2 2 86
我想为给定的 studentId 和 SubjectId 连接多行,将列标记为单个列,如下所示。
结果:
Id Name SubjectMarks
1 A 1:67,2:89
2 B 1:78,2:86
我试过了FOR XML PATH
。它适用于单列,但对于 2 列我无法编写查询。
MS SQL Server 2008 架构设置:
CREATE TABLE Student (Id INT, Name VARCHAR(10))
INSERT INTO Student VALUES
(1 ,'A'),
(2 ,'B')
CREATE TABLE Marks (StudentId INT , SubjectId INT , Marks INT)
INSERT INTO Marks VALUES
(1 , 1 , 67),
(1 , 2 , 89),
(2 , 1 , 78),
(2 , 2 , 86)
查询 1:
;WITH cte AS
(
SELECT StudentId
, CAST(SubjectId AS VARCHAR(10)) + ':'
+ CAST(Marks AS VARCHAR(10)) AS SubjectMarks
FROM Marks
)
SELECT DISTINCT
S.Id
,S.Name
,STUFF((SELECT ',' + SubjectMarks
FROM cte
WHERE x.StudentId = StudentId
FOR XML PATH(''),TYPE)
.value('.','Varchar(max)'),1,1,'') AS SubjectMarks
FROM cte x
INNER JOIN Student S ON S.Id = x.StudentId
| Id | Name | SubjectMarks |
|----|------|--------------|
| 1 | A | 1:67,2:89 |
| 2 | B | 1:78,2:86 |
你可以在没有 CTE 的情况下做到这一点:
select s.id, s.name,
stuff((select ',' + cast(subjectid as varchar(8000)) + ':' + cast(marks as varchar(8000))
from marks m
where m.studentid = s.id
for xml path (''), type
).value('.', 'varchar(max)'), 1, 1, ''
) as SubjectMarks
from student s;