Inilah salah satu cara untuk melakukannya.
Karena Anda juga menginginkan jumlah yang berbeda, itu dapat dilakukan hanya dengan mengelompokkan baris dua kali. GROUP BY
pertama akan menghapus duplikat, GROUP BY
kedua akan menghasilkan hasil akhir.
WITH
Sitings
AS
(
SELECT * FROM (VALUES
(1, 'Florida', 'Orlando', 'bird'),
(2, 'Florida', 'Orlando', 'dog'),
(3, 'Arizona', 'Phoenix', 'bird'),
(4, 'Arizona', 'Phoenix', 'dog'),
(5, 'Arizona', 'Phoenix', 'bird'),
(6, 'Arizona', 'Phoenix', 'bird'),
(7, 'Arizona', 'Phoenix', 'bird'),
(8, 'Arizona', 'Flagstaff', 'dog')
) F (ID, State, City, Siting)
)
,CTE_Animals
AS
(
SELECT
State, City, Siting
FROM Sitings
GROUP BY State, City, Siting
)
SELECT
State, City, COUNT(1) AS [# Of Sitings], STRING_AGG(Siting,',') AS Animals
FROM CTE_Animals
GROUP BY State, City
ORDER BY
State
,City
;
Hasil
+---------+-----------+--------------+----------+
| State | City | # Of Sitings | Animals |
+---------+-----------+--------------+----------+
| Arizona | Flagstaff | 1 | dog |
| Arizona | Phoenix | 2 | bird,dog |
| Florida | Orlando | 2 | bird,dog |
+---------+-----------+--------------+----------+
Jika Anda masih mendapatkan pesan kesalahan tentang melebihi 8000 karakter, masukkan nilainya ke varchar(max)
sebelum STRING_AGG
.
Sesuatu seperti
STRING_AGG(CAST(Siting AS varchar(max)),',') AS Animals