0

我有下表。

Student桌子:

Id          Name
1           A
2           B

Marks桌子:

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 列我无法编写查询。

4

2 回答 2

2

您可以在没有 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;
于 2015-08-15T19:38:56.020 回答
1

SQL小提琴

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 |
于 2015-08-15T19:25:28.810 回答