【问题标题】:Select rows in left join which depend on sum of a field in the other table?在左连接中选择取决于另一个表中字段总和的行?
【发布时间】:2021-02-04 16:30:21
【问题描述】:

我正在尝试编写一个 SQL 左外连接查询,其中左行是根据另一个(右)表中行中字段的总和来选择的。另一个表有一个 id 字段链接回左表,并且左表和右表之间存在一对多的关系。表格(仅简化为相关字段)如下所示:

左表:

+--------+
| id     |
| amount |
+--------+

right_table:

+-------------------+
| id                |
| amount            |
| left_table_row_id |
+-------------------+

基本上,右表行的金额字段具有左表中金额的分数,并关联回left_table,因此多个right_table 行可能链接到单个left_table 行。

我尝试仅选择 left_table 行,其中 left_table.id=right_table_id 其中 金额的总和right_table 的行中具有链接 ID 相等到left_table.amount。我们不能在 WHERE 子句中使用聚合,而且我在使用 HAVING 时运气不佳。我希望这是有道理的。

【问题讨论】:

    标签: sql postgresql subquery left-join aggregate-functions


    【解决方案1】:

    这应该可以通过以下查询实现:

    with agg as
    (
        select left_table_row_id,sum(amount) as amount
        from right_table
        group by left_table_row_id
    )
    select *
    from left_table lt
    where exists (select 1 from agg where lt.id=agg.left_table_row_id and lt.amount = agg.amount)
    

    【讨论】:

      【解决方案2】:

      您可以使用相关子查询进行过滤:

      select l.*
      from left_table l
      where l.amount = (select sum(r.amount) from right_table r where r.id = l.id)
      

      【讨论】:

      • 这比任何连接都简单 :-) 谢谢!
      猜你喜欢
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 2011-10-22
      • 1970-01-01
      • 2021-08-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多