上面是输入表。 我试图将所有childsku产品与其计数及其关联的父sku一起放在一行中。但它没有按预期工作
select [Parent SKU (PartNo) ],count([Child SKU]),[Child SKU]
from tbl_name
group by [Parent SKU (PartNo) ],[Child SKU]
现在我希望所需的输出如下:
答案 0 :(得分:2)
使用STUFF
。
<强>查询强>
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;
答案 1 :(得分:2)
您可以使用STUFF
;
测试数据;
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')
查询;
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
将结果作为;
ParentSKU ChildTotal ChildSKU
B001 4 B001L, B001M, B001S, B001XL