Grouped string aggregation / LISTAGG for SQL Server

末鹿安然 提交于 2019-12-17 06:43:47

问题


I'm sure this has been asked but I can't quite find the right search terms.

Given a schema like this:

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

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

I want to produce a dataset like this:

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

What do I do in place of 'AGG' for strings in SQL Server in the following style query?

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

回答1:


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

It is an interesting problem in Transact SQL, for which there are a number of solutions and considerable debate. How do you go about producing a summary result in which a distinguishing column from each row in each particular category is listed in a 'aggregate' column? A simple, and intuitive way of displaying data is surprisingly difficult to achieve. Anith Sen gives a summary of different ways, and offers words of caution over the one you choose...




回答2:


If it is SQL Server 2017 or SQL Server VNext, Azure SQL database you can use String_agg as below:

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

Output:

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


来源:https://stackoverflow.com/questions/3368942/grouped-string-aggregation-listagg-for-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!