Concatenation multiple rows and columns in SQL Server

rryofs0p  于 2023-06-28  发布在  SQL Server
关注(0)|答案(3)|浏览(159)

I have following tables.

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

I want to concat multiple rows for a given studentId and SubjectId, Marks columns into a single column as below.

Result:

Id          Name   SubjectMarks
1           A       1:67,2:89
2           B       1:78,2:86

I tried FOR XML PATH . It works for a single column, but for 2 columns I couldn't write a query.

xlpyo6sf

xlpyo6sf1#

You can do this without a 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;
6ju8rftf

6ju8rftf2#

SQL Fiddle

MS SQL Server 2008 Schema Setup:

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)

Query 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

Results:

| Id | Name | SubjectMarks |
|----|------|--------------|
|  1 |    A |    1:67,2:89 |
|  2 |    B |    1:78,2:86 |
368yc8dk

368yc8dk3#

thanks alot. sir.It was very useful for me. gh.

相关问题