【问题标题】:Getting sum of middle table columns in left join在左连接中获取中间表列的总和
【发布时间】:2021-05-07 11:26:46
【问题描述】:

下面是表格和 SQL 查询。我正在对 3 个表进行左连接,并尝试获取每个中间表中特定列的总和。但结果是错误的。

产品表:

id | product-name
-----------------
 1 | batman
 2 | goofy

尺寸-颜色表

id | product-id | size | color | total
---------------------------------------
 1 |    1       |  33  | blue  |  32
 2 |    1       |  33  | grey  |  11
 3 |    2       |  44  | blue  |  44
 4 |    2       |  33  | grey  |  11

销售表

id | size-color-id | sold-qty
-------------------------------
1  |     1         |    11
2  |     1         |     8
3  |     4         |     5     
4  |     4         |     2

我想获得每种产品的总金额已售出数量。我试过了:

select p.name, sum(c.total), sum(sold-qty)
from products p
LEFT join size-color c 
on p.id = c.product-id
left JOIN sells s
on c.id = s.size-color-id
GROUP by p.id

但我总共得到了错误的结果,因为我们在 size-color 表中重复了行。 谢谢

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    这有点复杂。您需要在“大小颜色”级别聚合sales 表。然后加入size_color,再次聚合:

    select p.name, sc.total, sc.qty
    from products p left join
         (select sc.product_id, sum(sc.total) as total,
                 sum(s.qty) as qty
          from size_color sc left join
               (select s.size_color_id, sum(sells) as sells
                from sells s
                group by s.size_color_id
               ) s
               on s.size_color_id = sc.id
          group by sc.product_id
         ) sc
         on sc.product_id = p.id;
    

    在您的查询版本中,size_color 中的总数乘以该id 的销售额。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多