问题描述
|
样品表:
ID产品
1勘测
1政策
1发票
2发票
2勘测
3政策
3发票
我最终想要得到的是一个带有三行的表(每个ID对应一个表),其中带有用逗号分隔的列表中的产品:
ID产品
1勘测,政策,发票
2发票,调查
3政策,发票
我可以使用用户定义的标量函数来执行此操作,但是它非常慢,我认为更合适的解决方案是使用游标,但这是我需要帮助的地方
解决方法
不确定速度与UDF或光标的关系,但是您可以尝试一下:
with T(ID,Product) as
(
select 1,\'Survey\' union all
select 1,\'Policy\' union all
select 1,\'Invoice\' union all
select 2,\'Survey\' union all
select 3,\'Policy\' union all
select 3,\'Invoice\'
)
select
T1.ID,stuff((select \',\'+T2.Product
from T as T2
where T1.ID = T2.ID
for xml path(\'\'),type).value(\'.\',\'nvarchar(max)\'),1,2,\'\') as Product
from T as T1
group by T1.ID
,可运行的示例:http://data.stackexchange.com/stackoverflow/q/101245/
DECLARE @tbl AS TABLE (ID int,Product VARCHAR(50))
INSERT INTO @tbl VALUES (
1,\'Survey\'),( 1,\'Policy\'),\'Invoice\'),( 2,( 3,\'Invoice\')
;WITH IDs AS (
SELECT ID
FROM @tbl
GROUP BY ID
)
SELECT IDs.ID,STUFF(Products.Products,\'\')
FROM IDs
OUTER APPLY (
SELECT \',\' + Product
FROM @tbl AS tbl
WHERE ID = IDs.ID
FOR XML PATH (\'\')
) AS Products (Products)