如何在postgresql中匹配列数,如果大于2,则更新表。

问题描述 投票:0回答:1

输入表 https:/i.stack.imgur.comeH6W3.jpg。 我要的输出表 https:/i.stack.imgur.comRsCb9.jpg。 我试过这样

update tb set Exception = 'Y'
select Card_No from tb
where Card_No in ( select Card_No from (select Card_No count(Left(Card_No,6)) from tb
group by Card_No having count(*)>=2)a);

上面的查询给我的操作是这样的 https:/i.stack.imgur.comvJ47z.jpg

sql string postgresql sql-update
1个回答
1
投票

你可以这样做。

update mytable 
set exception = case when cnt > 1 then 'Y' else 'N' end
from (
    select substring(card_no, 1, 6) sub_card_no, count(*) cnt 
    from mytable
    group by 1
) t
where t.sub_card_no = substring(mytable.card_no, 1, 6)

我可能会更有效地使用窗口函数。

update mytable 
set exception = case when cnt > 1 then 'Y' else 'N' end
from (
    select card_no, count(*) over(partition by substring(card_no, 1, 6)) cnt 
    from mytable
) t
where t.card_no = mytable.card_no
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.