查找 SQL 个具有特定条件的重复项

Find SQL duplicate with specific condition

我的 postgres sql 查询有问题。 我想找到具有特定条件的重复项。

id address_id state
12 1 A
94 1 A
991 1 A
992 2 A
993 2 A

条件: 我想根据 address_id 找到重复项,它们的状态应该是 'A'

所以我写了查询:

select count(*), g.address_id
            from tableName g
            where g.state = 'A'
            group by g.address_id
            having count(*)
                       > 1

当我想获取所有值时,我只是将查询扩展到:

SELECT w.* from tableName w
    (select count(*), g.address_id
                from tableName g
                where g.state = 'A'
                group by g.address_id
                having count(*)
                           > 1) x on w.address_id = x.address_id

在输出中我得到了所有重复项的列表。但我想获得具有最高 ID 的副本。

基于我的 table 我想得到输出 :

id address_id state
991 1 A
993 2 A

另一种方式:

select tn.id,tn.address_id,tn.state
from tableName tn
inner join (select max(id) as id ,count(address_id) as nr_count
            from tableName
            where state='A'
            group by address_id
            ) as t1 on tn.id=t1.id
where   t1.nr_count >1;   

Demo

您可以使用 window 函数:

select max(id) as id ,address_id,state
from (
   SELECT id, address_id,state
        , count(*) OVER ( PARTITION BY address_id  ) AS cnt
   FROM   tableName
   where state='A'
   ) as t1
where cnt>1
group by address_id,state;    

Demo