STRING_AGG 配合 WITHIN GROUP 的使用

 

syntax:

STRING_AGG ( expression, separator ) [ <order_clause> ]

<order_clause> ::=   
   WITHIN GROUP ( ORDER BY <order_by_expression_list> [ ASC | DESC ] )

 

一、STRING_AGG

範例:

select STRING_AGG(Name,', ') from 
(
    SELECT 1 AS No, 'Bill' AS Name, 30 AS age
    UNION
    SELECT 2 AS No, 'Mary' AS Name, 15 AS age
    UNION
    SELECT 3 AS No, 'Json' AS Name, 30 AS age
    UNION
    SELECT 4 AS No, 'Tim' AS Name, 15 AS age
) p

說明:

其用途為將某欄位的 n 筆記錄串成一筆記錄。

 

二、STRING_AGG 配合 WITHIN GROUP 的使用

範例:

select age, STRING_AGG(Name,', ') WITHIN GROUP (order by No desc) from 
(
    SELECT 1 AS No, 'Bill' AS Name, 30 AS age
    UNION
    SELECT 2 AS No, 'Mary' AS Name, 15 AS age
    UNION
    SELECT 3 AS No, 'Json' AS Name, 30 AS age
    UNION
    SELECT 4 AS No, 'Tim' AS Name, 15 AS age
) p
group by age

說明:

當你有使用到群組並想排序串記錄時,則可加上 WITHIN GROUP。

 

參考資料:

STRING_AGG (Transact-SQL)