Oracle Sql 查询以查找具有属性值但同时没有差异值的 id
Oracle Sql Query to find ids which has value of an attribute and at the same time not having diff values
您好团队,
我需要一个简单的查询,我可以在其中找到合同状态为 'C' 的合作伙伴 ID,它在 'A' 和 'B' 中没有任何合同状态。我需要找到第 3 行的合作伙伴 ID,因为合作伙伴 ID 2 没有 A 或 B 的任何合同状态。同样,我想过滤合同状态为 'A' 或 'B' 的合作伙伴 ID但不是合同状态 'C' 。也就是说,我需要第 5,6 行的合作伙伴 ID。提前致谢
一个选项使用 group by
和 having
:
select partnerid
from mytable
group by partnerid
having
max(case when contractstatus = 'A' then 1 else 0 end) = 1
and max(case when contractstatus in ('B', 'C') then 1 else 0 end) = 0
这可以用 where
子句简化:
select partnerid
from mytable
where contractstatus in ('A', 'B', 'C')
group by partnerid
having max(case when contractstatus in ('B', 'C') then 1 else 0 end) = 0
此 returns partnerid
状态为“A”,但不是“B”或“C”。如果您想要那些有“A”或“B”但没有“C”的那些,则只需将 having
子句更改为:
having max(case when contractstatus = 'C' then 1 else 0 end) = 0
如果合作伙伴 ID 和状态没有重复的行,您还可以使用 not exists
:
select t.*
from t
where t.status = 'C' and
not exists (select 1
from t t2
where t2.partnerid = t.partnerid and
t2.status in ('A', 'B')
);
另一种选择是使用分析函数 MAX
,如下所示:
SELECT *
FROM (SELECT T.*,
MAX(STATUS) OVER(PARTITION BY PARTNERID) AS MAX_STATUS
FROM T)
WHERE MAX_STATUS = 'A';
您好团队, 我需要一个简单的查询,我可以在其中找到合同状态为 'C' 的合作伙伴 ID,它在 'A' 和 'B' 中没有任何合同状态。我需要找到第 3 行的合作伙伴 ID,因为合作伙伴 ID 2 没有 A 或 B 的任何合同状态。同样,我想过滤合同状态为 'A' 或 'B' 的合作伙伴 ID但不是合同状态 'C' 。也就是说,我需要第 5,6 行的合作伙伴 ID。提前致谢
一个选项使用 group by
和 having
:
select partnerid
from mytable
group by partnerid
having
max(case when contractstatus = 'A' then 1 else 0 end) = 1
and max(case when contractstatus in ('B', 'C') then 1 else 0 end) = 0
这可以用 where
子句简化:
select partnerid
from mytable
where contractstatus in ('A', 'B', 'C')
group by partnerid
having max(case when contractstatus in ('B', 'C') then 1 else 0 end) = 0
此 returns partnerid
状态为“A”,但不是“B”或“C”。如果您想要那些有“A”或“B”但没有“C”的那些,则只需将 having
子句更改为:
having max(case when contractstatus = 'C' then 1 else 0 end) = 0
如果合作伙伴 ID 和状态没有重复的行,您还可以使用 not exists
:
select t.*
from t
where t.status = 'C' and
not exists (select 1
from t t2
where t2.partnerid = t.partnerid and
t2.status in ('A', 'B')
);
另一种选择是使用分析函数 MAX
,如下所示:
SELECT *
FROM (SELECT T.*,
MAX(STATUS) OVER(PARTITION BY PARTNERID) AS MAX_STATUS
FROM T)
WHERE MAX_STATUS = 'A';