【问题标题】:Oracle Sql Counting Rows in a Table based on duplicates in another tableOracle Sql 根据另一个表中的重复项计算表中的行数
【发布时间】:2020-08-12 22:04:28
【问题描述】:

我在 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 中的每个状态,在 t1 中具有少于三行的 ID。 在这个例子中:

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 

谢谢!

【问题讨论】:

    标签: sql oracle


    【解决方案1】:

    根据您的条件在每个表中单独聚合,然后加入以聚合不同 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()窗口函数:

    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"
    

    请参阅demo
    结果:

    > state | COUNTER
    > :---- | ------:
    > VA    |       1
    > MI    |       0
    

    【讨论】:

    • 感谢您的反馈。我正在使用模式中的表,所以我不确定我的语法是否正确。我继续在 schema.t1 左连接处收到语法错误,显示“where_clause”和“unbalanced_nonblock_stmt”。下面是我的查询:select A.state, count(distinct B.ID) counter from (select ID, state from schema.t1 group by ID, state have count() > 1) schema.t1 left join (select ID,state from schema.t2 group by ID, state have count()
    • 改成这个:select A.state, count(distinct B.ID) counter from ( select ID, state from schema.t1 group by ID, state having count(*) &gt; 1 ) A left join ( select ID, state from schema.t2 group by ID, state having count(*) &lt; 3 ) B on A.ID = B.ID and A.state = B.state group by A.state
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多