[英]Oracle Remove Duplicates and Update Rows in a Table with a Value from Another Table
[英]Oracle Sql Counting Rows in a Table based on duplicates in another table
我在 Oracle SQL Developer 中有两个表,它们由键 ID + 状态连接。 第一个 (t1) 有 4 列:
ID measurement Value state
123 Nitrogen .7 VA
123 Oxygen .1 VA
456 Nitrogen .6 MI
456 Carbon .5 MI
456 Oxygen .3 MI
第二个表 (t2) 有 3 列:
ID date state
123 5/20/20 VA
123 8/3/16 VA
我需要编写一个查询,首先在 t2 中搜索重复的 ID+状态,然后在第二个表中搜索具有少于三行的重复 ID+状态的实例。 返回将是 t2 中重复的 ID 计数,并且对于 t2 中的每个 state,在 t1 中的行数少于三行。 在这个例子中:
VA - 1
MI - 0
在 Oracle 中是否有一种简单的方法可以做到这一点? 我已经尝试过以下 SQL 的迭代,并且无法找到正确的语法,并且想知道是否有更好的方法。 我尝试了以下查询的多次迭代:
select a.ID, a.state count() totalcount from t2 A left join t1 B on a.ID=b.ID and a.state=b.state where b.ID having count < 3 group by a.id having count () >1
谢谢!
根据您的条件在 eah 表中单独聚合,然后加入以聚合不同 id 的数量:
select t1.state, count(distinct t2.id) counter
from (
select id, state from t1
group by id, state
having count(*) > 1
) t1 left join (
select id, state from t2
group by id, state
having count(*) < 3
) t2
on t2.id = t1.id and t2.state = t1.state
group by t1.state
或者使用COUNT()
window function:
select t1."state", count(distinct t2.id) counter
from (
select id, "state",
count(*) over (partition by id, "state") counter1
from t1
) t1 left join (
select id, "state",
count(*) over (partition by id, "state") counter2
from t2
) t2
on t2.id = t1.id and t2."state" = t1."state"
and t1.counter1 > 1 and t2.counter2 < 3
group by t1."state"
请参阅演示。
结果:
> state | COUNTER
> :---- | ------:
> VA | 1
> MI | 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.