【问题标题】:How to match count of column and if greater than 2 then update table in postgresql如何匹配列数,如果大于 2,则更新 postgresql 中的表
【发布时间】:2020-04-22 16:25:48
【问题描述】:

输入表
https://i.stack.imgur.com/eH6W3.jpg
我想要的输出表
https://i.stack.imgur.com/RsCb9.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.com/vJ47z.jpg

【问题讨论】:

    标签: sql string postgresql select sql-update


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-18
      • 1970-01-01
      相关资源
      最近更新 更多