将多个连接列分组返回到逗号分隔的字符串列

时间:2016-12-14 18:42:35

标签: sql-server tsql sql-server-2012

我有下表

Year, Category,   CarID,  CarName,   Milage
--------------------------------------------
2012  GroupA       1     Porsche      100
2012  GroupA       2     Mercedes     200
2013  GroupA       3     Ferrari      300
2013  GroupB       4     Uno          200
2013  GroupB       5     Beetle       200

我想在Year和Category上输出分组,并将Car Names和milage作为显示列返回

Year, Category, DisplayString
--------------------------------------------
2012  GroupA    Mercedes (200km), Porsche (100km)  
2013  GroupA    Ferrari (300km)
2013  GroupB    Beetle (200km), Uno (200km)

我正在尝试将a columns to comma delimited string与一个组合以及多个类型列连接起来,但我不确定如何继续。我正在使用SQL Server 2012。

2 个答案:

答案 0 :(得分:3)

Select A.*
      ,DistplayString = (Select Stuff((Select Distinct concat(', ',CarName,' (',Milage,'km)') 
                                        From  YourTable 
                                        Where Year=A.Year and Category=A.Category 
                                        For XML Path ('')),1,2,'') )
 From (Select Distinct Year, Category From YourTable) A

返回(感谢Alan的表变量+1)

Year    Category    DistplayString
2012    GroupA      Mercedes (200km), Porsche (100km)
2013    GroupA      Ferrari (300km)
2013    GroupB      Beetle (200km), Uno (200km)

答案 1 :(得分:2)

约翰打败了我。这几乎与引擎盖下的解决方案相同。

-- Your Sample Data
DECLARE @yourtable TABLE 
(
  [year]   smallint, 
  category varchar(10), 
  CarID    int, 
  CarName  varchar(20), 
  Milage   int
);

INSERT @yourtable
VALUES 
(2012,'GroupA',1,'Porsche',  100),
(2012,'GroupA',2,'Mercedes', 200),
(2013,'GroupA',3,'Ferrari',  300),
(2013,'GroupB',4,'Uno',      200),
(2013,'GroupB',5,'Beetle',   200);

-- Solution
SELECT 
  [Year], 
  Category, 
  DisplayString = 
  STUFF
  ((
    SELECT CONCAT(', ', Carname, ' (', milage, 'km)')
    FROM @yourtable i WHERE o.[year] = i.[year] AND o.category = i.category
    FOR XML PATH('')
  ),1,2,'')
FROM @yourtable o
GROUP BY [year], category;

返回:

Year   Category   DisplayString
------ ---------- ---------------------------------
2012   GroupA     Porsche (100km), Mercedes (200km)
2013   GroupA     Ferrari (300km)
2013   GroupB     Uno (200km), Beetle (200km)