0

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.

2 Answers 2

2

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;
Sign up to request clarification or add additional context in comments.

Comments

1

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 |

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.