0

可能重复:
将行值合并到 CSV(又名 GROUP_CONCAT 用于 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

我怎样才能做到这一点?

4

1 回答 1

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
于 2012-12-14T07:33:25.357 回答