Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Snowflake SQL: concat values from multiple rows based on shared key

I have a table of values where there are a variable number of rows per each key value. I want to output a table that concats those row values together onto each distinct key value.

INPUT TABLE

KEY_ID SOURCE_VAL
1 a
1 b
1 c
2 d
3 e
3 f

Target OUTPUT TABLE

KEY_ID OUTPUT_VAL
1 a,b,c
2 d
3 e,f

What is the most efficient way to write this in Snowflake SQL?

like image 614
Declan Avatar asked Apr 17 '26 16:04

Declan


1 Answers

It could be done with LISTAGG:

SELECT KEY_ID, 
       LISTAGG(SOURCE_VAL, ',') WITHIN GROUP(ORDER BY SOURCE_VAL) AS OUTPUT_VAL
FROM tab
GROUP BY KEY_ID
like image 85
Lukasz Szozda Avatar answered Apr 20 '26 09:04

Lukasz Szozda