从表中获取与列精确匹配1个的记录

时间:2018-08-30 10:00:12

标签: sql oracle

我有一个协议详细信息表,其中有AgreementID。协议ID可以基于其他值重复。如何仅获取其中只有1 AgreementID的行?以下是我正在使用的查询,但没有返回我想要的结果。

select AGREEMENT_ID  from Agreement_Detail
GROUP BY  AGREEMENT_ID  Having COUNT(*) = 1 

我想念什么吗?

样本数据:

如果Agreement_ID为1,则详细信息表中的内容可以重复

Agreement_ID    Pid
1               2
1               3
1               4

此外,可以有如下所示的Agreement_ID为2

Agreement_ID    Pid
2               2

我想要这个2作为我的结果。

5 个答案:

答案 0 :(得分:0)

您似乎想要not exists

select ad.*
from Agreement_Detail ad
where not exists (select 1 
                  from Agreement_Detail ad1 
                  where ad1.AGREEMENT_ID = ad.AGREEMENT_ID and ad1.Pid <> ad.Pid
                 );

但是,您也可以使用GROUP BY

select AGREEMENT_ID
from Agreement_Detail ad
group by AGREEMENT_ID
having min(pid) = max(pid);

答案 1 :(得分:0)

请尝试以下查询:

select pid, count(AGREEMENT_ID)
group by pid
having count(AGREEMENT_ID)>1

答案 2 :(得分:0)

在您的代码中,不要对协议ID进行group by,而对PID进行group by,并将条件设为having count(Agreement Id) >1

答案 3 :(得分:0)

这是您需要的: 您需要为每个AGREEMENT_ID设置COUNT的出价

SELECT tab1.*
FROM Agreement_Detail tab1 JOIN 
   (
    select AGREEMENT_ID, count(PID) As PID
    from Agreement_Detail
    GROUP BY  AGREEMENT_ID 
    having count(PID) = 1
   ) tab2 
ON tab1.AGREEMENT_ID = tab2.AGREEMENT_ID

答案 4 :(得分:0)

一种可能的方式:

select Agreement_ID, Pid from (
    select Agreement_ID, Pid, count(*) over(partition by Agreement_ID) as cnt from Agreement_Detail
) t
where cnt = 1