I have a table that has 3 columns (ID
, key
, value
):
key
has repeated text, but value
does not.
How do I combine/append the texts of value
into one field according to key
, separating them with a comma or newline, and delete the repeated texts of key
?
If the order of the values in the results is not important, then you can do it with aggregation and GROUP_CONCAT()
, which in SQLite does not support an ORDER BY
clause and the order of the values is not guaranteed:
SELECT MIN(ID) ID, key, GROUP_CONCAT(value) value
FROM tablename
GROUP BY key
If you need the values ordered by ID
, then use GROUP_CONCAT()
window function:
SELECT DISTINCT
MIN(ID) OVER (PARTITION BY key) ID,
key,
GROUP_CONCAT(value) OVER (
PARTITION BY key
ORDER BY ID
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) value
FROM tablename