问题描述:

This question already has an answer here:

  • DB2 comma separated output

    7 answers

网友答案:

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;
相关阅读:
Top