0

I have the input table like this

Above is the input table. I am trying to bring all the childsku products in a single row with its count and its associated parent sku.But it is not working as expected

         select [Parent SKU (PartNo) ],count([Child SKU]),[Child SKU] 
from tbl_name
       group by [Parent SKU (PartNo) ],[Child SKU]

Now I want the desired output to be like this:

Desired Output

Marin Mohanadas
  • 163
  • 1
  • 7
sql_lover
  • 127
  • 10

2 Answers2

2

Use STUFF.

Query

SELECT t.ParentSKU, COUNT(t.ChildSKU) as Total,
STUFF((
    SELECT ',' + ChildSKU
    FROM tbl_name 
    WHERE ParentSKU = t.ParentSKU
    FOR XML PATH('')
), 1, 1, '') AS ChildSKU
FROM tbl_name t
GROUP BY ParentSKU;

Demo

Community
  • 1
  • 1
Ullas
  • 11,450
  • 4
  • 33
  • 50
2

You can use STUFF for this;

Test Data;

IF OBJECT_ID('tempdb..#TestData') IS NOT NULL DROP TABLE #TestData
GO
CREATE TABLE #TestData (ChildSKU varchar(10), ParentSKU varchar(10))
INSERT INTO #TestData (ChildSKU, ParentSKU)
VALUES
('B001L','B001')
,('B001M','B001')
,('B001S','B001')
,('B001XL','B001')

Query;

SELECT 
a.ParentSKU
,COUNT(ChildSKU) ChildTotal
,STUFF((SELECT ', ' + ChildSKU
           FROM #TestData b 
           WHERE b.ParentSKU = a.ParentSKU 
          FOR XML PATH('')), 1, 2, '') AS ChildSKU
FROM #TestData a
GROUP BY ParentSKU

Gives the results as;

ParentSKU   ChildTotal  ChildSKU
B001        4           B001L, B001M, B001S, B001XL
Rich Benner
  • 7,873
  • 9
  • 33
  • 39