【问题标题】:sql multiple left joins with sumsql多个左连接与sum
【发布时间】:2020-11-18 12:35:52
【问题描述】:

我有 3 张桌子,如下所示。我需要做的是在将第一个表与第二个表和第二个表与第三个表左连接后创建一个摘要。

我使用的代码最终导致了笛卡尔连接。我创建第一个表(人)的查询很复杂且资源密集,而表 2(购物清单)的数据量很大,因此嵌套查询并不理想。下面是我现在正在使用的代码以及预期的输出(图 1)和我得到的(图 2)

select
   a.ID,
   a.Name,
   sum(b.cost) total_cost,
   sum(c.discount_amount) total_discount
from
   person a,
   left join shopping_list b on a.id=b.id
   left join discount c on b.item = c.item
group by
   a.ID,
   a.Name

我查看了以下链接,但我希望有一个解决方案可以更好地考虑我的数据集的大小

https://dba.stackexchange.com/questions/217220/how-i-use-multiple-sum-with-multiple-left-joins

Multiple Left Join with sum

提前感谢您的帮助

【问题讨论】:

    标签: sql


    【解决方案1】:

    您有多行折扣,所以先总结一下:

    select p.id, p.name, coalesce(sl.cost, 0) as cost,
           coalesce(d.discount_amount, 0) as discount_amount
    from person p left join
         shopping_list sl
         on sl.id = p.id left join
         (select d.item, sum(discount_amount) as discount_amount
          from discount
          group by d.item
         ) d
         on sl.item = d.item
    group by p.id, p.name;
    

    您的查询的问题是discount 的多行最终与shopping_list 的行相乘——导致总数不准确。

    请注意,在此查询中,表别名是表名的缩写。这是一种最佳实践,可以让您更轻松地遵循查询逻辑。

    【讨论】:

      猜你喜欢
      • 2017-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-28
      • 2021-09-02
      • 1970-01-01
      • 2015-04-04
      相关资源
      最近更新 更多