对于DB2
如何获取每行包含“Y”的列名并将它们连接到以逗号分隔的列表中?
例如,当基表看起来像这样:
person | apple | orange | grapes
--------------------------------
1 Y Y
2 Y
3 Y
查询结果需要如下所示:
person | fruits
---------------------------
1 apple,orange
2 orange
3 grapes
我尝试了COALESCE
,但这不起作用,因为它会合并为Y.
我试过CASE WHEN f.apple ='Y' THEN 'apple'
WHEN f.orange = 'Y' THEN 'orange'
WHEN f.grapes = 'Y' THEN 'grapes'
END AS fruits
但上述内容只会返回一个WHEN陈述。
我试过CASE WHEN f.apple ='Y' THEN concat('apple,')
WHEN f.orange = 'Y' THEN concat('orange,')
when f.grapes = 'Y' THEN concat('grapes,')
END AS fruits
但这显然不起作用,因为它是一个语法错误(对SQL而言是新的),但仍然只有一个WHEN
可以工作。
答案 0 :(得分:0)
如果每个人的值可以表示为多行表达式,LISTAGG
聚合函数将快速完成此任务:
WITH fruitCTE (person, fruitname) AS (
SELECT person, 'apple' FROM originalTable WHERE apple = 'Y'
UNION ALL
SELECT person, 'orange' FROM originalTable WHERE orange = 'Y'
UNION ALL
SELECT person, 'grapes' FROM originalTable WHERE grapes = 'Y'
)
SELECT person,
LISTAGG( fruitname, ',' )
WITHIN GROUP ( ORDER BY fruitname ASC )
AS fruits
FROM fruitCTE
GROUP BY person
;
如果您的查询还需要显示根本没有Y标记的人,您可以修改最终/外SELECT
以执行从LEFT OUTER JOIN
到{{1}的originalTable
在fruitCTE
列上。