This question already has answers here:
Closed 7 years ago.
How do I concatenate multiple rows into a single row using SQL? My database is DB2
TableFoo
-------
Id Name
1 Apples
1 Tomatoes
1 Potatoes
2 Banana
2 Peach
I want something like
ID FruitsAvailable
-------------------------
1 Apples, Tomatoes, Potatoes
try this
SELECT id ,FruitsAvailable
FROM
(SELECT id , group_concat(Name) as FruitsAvailable
FROM TableFoo
WHERE id = 1) t
HERE DEMO SQLFIDDLE
EDIT:
in db2 you need to create function and then call it
CREATE FUNCTION MySchema/MyUDF (
PARCol2 CHAR(5) )
RETURNS VARCHAR(1024)
LANGUAGE SQL
NOT DETERMINISTIC
READS SQL DATA
CALLED ON NULL INPUT
DISALLOW PARALLEL
BEGIN
DECLARE ReturnVal VARCHAR(1024) NOT NULL DEFAULT '';
FOR CsrC1 AS C1 CURSOR
FOR SELECT MyCol1
FROM MyTable
WHERE MyCol2 = ParCol2
DO SET ReturnVal = ReturnVal Concat CsrC1.MyCol1;
END FOR;
RETURN LTRIM(ReturnVal);
END ;
and then call it here
Select id, MyUDF(Name) as FruitsAvailable
From TableFoo
where id = 1
Use this query:
SELECT Id, GROUP_CONCAT(Name SEPARATOR ', ') FROM TableFoo GROUP BY Id;