Grouped string aggregation / LISTAGG for SQL Server

前端 未结 2 519
暖寄归人
暖寄归人 2020-11-29 06:46

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

Given a schema like this:

| CarMakeID | CarMake
----------------------         


        
相关标签:
2条回答
  • 2020-11-29 07:17

    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 |
    +-----------+-----------+---------------------------+
    
    0 讨论(0)
  • 2020-11-29 07:24

    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...

    0 讨论(0)
提交回复
热议问题