6

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
Zo Has
  • 12,599
  • 22
  • 87
  • 149

2 Answers2

7

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 
echo_Me
  • 37,078
  • 5
  • 58
  • 78
  • 1
    -1: GROUP_CONCAT is MySql, it doesn't exist in DB2 – Daniel Hilgarth Feb 13 '13 at 10:21
  • Can't get it to work. I think group_concat is not supported on DB2 – Zo Has Feb 13 '13 at 10:21
  • Thanks! Is using a cursor necessary? – Zo Has Feb 13 '13 at 10:45
  • I am having a problem with this, The function keeps returning "++++++++++" no matter what I give it and I tried changing around quite a lot of stuff but it keeps doing that. Anyone have any ideas? – Steven Rogers Jun 17 '16 at 23:08
  • @StevenRogers yeah...ditch DB2. That's what my company is doing and it's not a minute too soon. – cbmeeks Jan 12 '17 at 14:26
  • 1
    @cbmeeks This is a client's database. They already denied switching and are sticking to it like glue. I was able to find a workaround for my last comment a few days after it was posted, wish I remembered what it was so I could share it with the world. – Steven Rogers Jan 12 '17 at 18:05
-3

Use this query:

SELECT Id, GROUP_CONCAT(Name SEPARATOR ', ') FROM TableFoo GROUP BY Id;