我需要这个基于场景的查询。
SalesID Line Noofitems Category Desc
SID12345 1 1 Metal-SI Strong iron
SID12345 2 1 Plastic Disposal
SID12345 3 1 Plastic Disposal
预期产出
SalesID Totitems Category Desc
SID12345 3 Metal-SI,Plastic Strong iron,Disposal
答案 0 :(得分:0)
您可以在此处使用for xml path
方法,使用distinct
子句删除重复项,同时连接列值,然后group by
上的SalesID
查询将如下:
select
SalesID,
sum(Noofitems) as Totitems,
STUFF(
(
Select
DISTINCT ','+t1.Category
from tbl t1
where t1.SalesID=t2.SalesID
for xml path('')
),1,1,'')
as Category,
STUFF(
(
select
DISTINCT ','+t1.[Desc]
from tbl t1
where t1.SalesID=t2.SalesID
for xml path('')
),1,1,'')
as [Desc]
from tbl t2
group by SalesID
demo sql fiddle的链接:http://sqlfiddle.com/#!6/d6bf5/8
在内部查询中使用order by
来更改连接字符串的顺序。