我需要这个基于场景的查询。
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发布于 2015-08-30 11:14:03
在这里,您可以使用for xml path方法,在连接列值时使用distinct子句删除重复项,然后在SalesID上使用group by
查询将类似于:
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 SalesIDsql fiddle演示链接:http://sqlfiddle.com/#!6/d6bf5/8
在内部查询中使用order by更改连接字符串的顺序。
https://stackoverflow.com/questions/32292718
复制相似问题