样本表:
ID 产品
1个调查
1个政策
1个发票
2个发票
2调查
3个政策
3发票
我最想得到的是一张带有3行(每个ID一个)的表格,其中包含以逗号分隔的列表中的产品:
ID 产品
1调查,政策,发票
2发票,调查
3政策,发票
我能够用一个用户定义的标量函数来做这个,但它很慢,我相信更合适的解决方案就是光标,但这就是我需要帮助的地方
答案 0 :(得分:4)
不确定速度与UDF或光标,但您可以尝试一下:
with T(ID, Product) as
(
select 1, 'Survey' union all
select 1, 'Policy' union all
select 1, 'Invoice' union all
select 2, '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
答案 1 :(得分:1)
可运行示例:http://data.stackexchange.com/stackoverflow/q/101245/
DECLARE @tbl AS TABLE (ID int, Product VARCHAR(50))
INSERT INTO @tbl VALUES (
1 ,'Survey'),
( 1 ,'Policy'),
( 1 ,'Invoice'),
( 2 ,'Invoice'),
( 2 ,'Survey'),
( 3 ,'Policy'),
( 3 ,'Invoice')
;WITH IDs AS (
SELECT ID
FROM @tbl
GROUP BY ID
)
SELECT IDs.ID, STUFF(Products.Products, 1, 1, '')
FROM IDs
OUTER APPLY (
SELECT ',' + Product
FROM @tbl AS tbl
WHERE ID = IDs.ID
FOR XML PATH ('')
) AS Products (Products)