如何使用 SQL 将多行连接成单行?我的数据库是 DB2
TableFoo
-------
Id Name
1 Apples
1 Tomatoes
1 Potatoes
2 Banana
2 Peach
我想要类似的东西
ID FruitsAvailable
-------------------------
1 Apples, Tomatoes, Potatoes
试试这个
SELECT id ,FruitsAvailable
FROM
(SELECT id , group_concat(Name) as FruitsAvailable
FROM TableFoo
WHERE id = 1) t
编辑:在 db2 中你需要创建函数然后调用它
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 ;
然后在这里调用
Select id, MyUDF(Name) as FruitsAvailable
From TableFoo
where id = 1
使用此查询:
SELECT Id, GROUP_CONCAT(Name SEPARATOR ', ') FROM TableFoo GROUP BY Id;