1

I have a 1:M recordset that I need to pivot into columns where the results are concatenated.

Create sample data:

CREATE TABLE #temptable 
(
    ID int,
    Division int,
    Material int
);

 insert into #temptable
 Values
 (999, 1, 1)
 ,(999, 1, 2)
 ,(999, 1, 3)
 ,(999, 2, 1)
 ,(999, 2, 6)
 ,(999, 3, 2)

Sample data:

ID     Division     Material   
----  ----------   ----------   
999       1            1          
999       1            2
999       1            3
999       2            1
999       2            6
999       3            2

I need the results to look like this, where the materials for each division are concatenated:

 ID   Division-1   Division-2   Division-3
----  ----------   ----------   ----------
999     1,2,3          1,6          2
3
  • 3
    did you try any thing ? Commented Jul 5, 2017 at 18:20
  • And what version of SQL? Commented Jul 5, 2017 at 18:44
  • Kamran's answer below solved the question. Commented Jul 5, 2017 at 20:25

1 Answer 1

1

Try this :

SELECT ID,
       [1] AS 'Division-1',
       [2] AS 'Division-2',
       [3] AS 'Division-3'
FROM
(
    SELECT DISTINCT
           a.ID,
           a.Division,
           LEFT(r.ResourceName, LEN(r.ResourceName) - 1) ResourceName
    FROM #temptable a
         CROSS APPLY
    (
        SELECT CAST(Material AS VARCHAR(10))+','
        FROM #temptable t
        WHERE a.[ID] = t.[ID]
              AND a.Division = t.Division
        FOR XML PATH('')
    ) r(ResourceName)
) src PIVOT(MAX(ResourceName) FOR Division IN([1],
                                              [2],
                                              [3])) piv; 

brief explanation We need to create pivot over comma separated structure.

Below query converts column value into comma separated rows.

SELECT a.ID,
       a.Division,
       LEFT(r.ResourceName, LEN(r.ResourceName) - 1) ResourceName
FROM #temptable a
     CROSS APPLY
(
    SELECT CAST(Material AS VARCHAR(10))+','
    FROM #temptable t
    WHERE a.[ID] = t.[ID]
          AND a.Division = t.Division
    FOR XML PATH('')
) r(ResourceName);

After that we create pivot over it.

Sign up to request clarification or add additional context in comments.

2 Comments

This is excellent, way beyond my kung-fu level. Thank you very much.
@ScottM : If it helped, mark it as answer in case people stumble upon

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.