-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstring-agg-function.sql
57 lines (41 loc) · 1.13 KB
/
string-agg-function.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
USE WideWorldImporters
GO
-- Aggregate Customer Categories into a comma separated values list
SELECT
STRING_AGG(CustomerCategoryName, ',') AS Aggregate_List
FROM
Sales.CustomerCategories
GO
-- Aggregate Email Addresses into a comma separated values list
-- But there's an error... s#%t
SELECT
STRING_AGG(pe.EmailAddress, ',') AS Aggregate_List
FROM
Application.People AS pe
GO
-- Aggregate Email Addresses into a comma separated values list... Fixed it!
SELECT
STRING_AGG(CAST(pe.EmailAddress AS NVARCHAR(MAX)), ',') AS Aggregate_List
FROM
Application.People AS pe
GO
-- Not using WITHIN GROUP
SELECT
st.StateProvinceName
, STRING_AGG(CAST(c.CityName AS NVARCHAR(MAX)), ', ') AS Cities
FROM
Application.Cities AS c
INNER JOIN
Application.StateProvinces AS st
ON c.StateProvinceID = st.StateProvinceID
GROUP BY st.StateProvinceName
-- Using WITHIN GROUP
SELECT
st.StateProvinceName
, STRING_AGG(CAST(c.CityName AS NVARCHAR(MAX)), ', ') WITHIN GROUP(ORDER BY c.CityName ASC) AS Cities
FROM
Application.Cities AS c
INNER JOIN
Application.StateProvinces AS st
ON c.StateProvinceID = st.StateProvinceID
GROUP BY st.StateProvinceName