可能重复:
Merge row values into a CSV (a.k.a GROUP_CONCAT for SQL Server)
基本上有一些不同领域的相同数据。我们的客户想要合并那种数据。我在下面展示了它。
season_id | service_id | service_name | product_line | service_date
10-12/11 | PIM0768 | Hilton NYC | H | 2012-03-02
10-12/11 | PIM0954 | Hilton NYC | AB1 | 2012-03-02
season_id | service_id | service_name | product_line | service_date
10-12/11 | PIM0768,PIM0954 | Hilton NYC | H,AB1 | 2012-03-02
我该怎么做?
答案 0 :(得分:1)
CREATE TABLE #tmp (season_id varchar(10), service_id Varchar(10), service_name varchar(30), product_line varchar(10), service_date datetime)
INSERT INTO #tmp VALUES ('10-12/11','PIM0768','Hilton NYC','H','20120302')
INSERT INTO #tmp VALUES ('10-12/11','PIM0954','Hilton NYC','ABC','20120302')
SELECT
season_id,
cast(
STUFF((
SELECT ', ' + service_id
FROM #tmp
WHERE (season_id = Results.season_id)
FOR XML PATH (''))
,1,2,'')as Varchar(max)) AS service_id
,service_name
,Cast(STUFF((
SELECT ', ' + product_line
FROM #tmp
WHERE (season_id = Results.season_id)
FOR XML PATH (''))
,1,2,'')as Varchar(max)) AS product_line
,service_date
FROM #tmp Results
GROUP BY season_id,service_name,service_date
Drop table #tmp