我正在努力寻找一种在红移中DISTINCT
listagg
的好方法。
我想要做的就是列出产品组合,但每一行都应该返回不同产品的列表。
示例
期望的输出:
bulb, light
bulb, light, fan
而不是:
bulb, bulb, light
bulb, bulb, light, fan
下面是我的SQL:
select
tit.listagg
from (
SELECT
username,
listagg(node_name, ',')
WITHIN GROUP (ORDER BY node_name asc)
FROM table
Where node_type not like '%bla bla%'
GROUP BY username
) as tit
group by listagg;
答案 0 :(得分:6)
您可以枚举行,然后选择第一行:
select username,
listagg(case when seqnum = 1 then node_name end, ',') within group (order by node_name asc)
from (select t.*,
row_number() over (partition by username, node_name order by node_name) as seqnum
from table t
where node_type not like '%bla bla%'
) t
group by username;
这使用listagg()
忽略NULL
值的功能。
答案 1 :(得分:1)
Redshift现在支持LISTAGG DISTINCT,因此不需要子查询:https://aws.amazon.com/about-aws/whats-new/2017/10/amazon-redshift-announces-support-for-listagg-distinct/