2012-12-14 145 views
0
合併數據

可能重複:
Merge row values into a CSV (a.k.a GROUP_CONCAT for SQL Server)與不同領域

Basicly有一些不同領域的一些相同的數據。我們的客戶想要合併這種數據。我已經在下面展示了它。

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 

我該怎麼做?

回答

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