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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With