SQL Server的分组字符串聚合/ LISTAGG

时间:2010-07-30 05:44:18

标签: sql sql-server aggregate-functions

我确信这已被问到,但我找不到合适的搜索字词。

给出这样的架构:

| CarMakeID | CarMake
------------------------
|         1 | SuperCars
|         2 | MehCars

| CarMakeID | CarModelID | CarModel
-----------------------------------------
|         1 |          1 | Zoom
|         2 |          1 | Wow
|         3 |          1 | Awesome
|         4 |          2 | Mediocrity
|         5 |          2 | YoureSettling

我想生成这样的数据集:

| CarMakeID | CarMake   | CarModels
---------------------------------------------
|         1 | SuperCars | Zoom, Wow, Awesome
|         2 | MehCars   | Mediocrity, YoureSettling

在以下样式查询中,如何代替SQL Server中的字符串'AGG'?

SELECT *, 
 (SELECT AGG(CarModel) 
  FROM CarModels model
  WHERE model.CarMakeID = make.CarMakeID
  GROUP BY make.CarMakeID) as CarMakes
FROM CarMakes make

2 个答案:

答案 0 :(得分:11)

http://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/

  

这是Transact SQL中一个有趣的问题,有许多解决方案和相当多的争论。如何生成汇总结果,其中每个特定类别中每行的区别列列在“汇总”列中?显然,难以实现简单直观的数据显示方式。 Anith Sen总结了不同的方法,并对你选择的方式提出了谨慎的言辞......

答案 1 :(得分:4)

如果是SQL Server 2017或SQL Server VNext,Azure SQL数据库可以使用String_agg,如下所示:

SELECT  make.CarMakeId, make.CarMake, 
        CarModels = string_agg(model.CarModel, ', ') 
FROM CarModels model
    INNER JOIN CarMakes make 
    ON model.CarMakeId = make.CarMakeId
GROUP BY make.CarMakeId, make.CarMake

输出:

+-----------+-----------+---------------------------+
| CarMakeId |  CarMake  |         CarModels         |
+-----------+-----------+---------------------------+
|         1 | SuperCars | Zoom, Wow, Awesome        |
|         2 | MehCars   | Mediocrity, YoureSettling |
+-----------+-----------+---------------------------+