【问题标题】:Mysql Database: Joins sums and group byMysql 数据库:加入 sums 和 group by
【发布时间】:2021-01-13 12:38:38
【问题描述】:

我有两张表 OrderUpdate 和 DailyProduction

ORDER_UPDATE

itemid  packages    ordercode
1       10          ORANGE
2       20          ORANGE
3       40          ORANGE
1       25          APPLE
2       50          APPLE
3       100         APPLE

每日生产

date    itemid  packages    ordercode
28-Sep  1       5           ORANGE
20-Sep  1       2           ORANGE
1-Sep   3       4           ORANGE
1-Sep   1       5           APPLE
15-Sep  2       5           APPLE
30-Sep  3       1           APPLE

结果我想要关注

itemid  packages    ordercode   ready   remaining
1       10          ORANGE      7       3
2       20          ORANGE      0       20
3       40          ORANGE      4       36
1       25          APPLE       5       20
2       50          APPLE       5       45
3       100         APPLE       1       99

【问题讨论】:

标签: mysql sql group-by sum left-join


【解决方案1】:

如果我没听错的话,您可以在 left joinorder_update 中使用聚合查询来汇总表 daily_production 中每个 (itemid, ordercode) 的包:

select ou.*, coalesce(dp.ready, 0), ou.packages - coalesce(dp.ready, 0) reamining 
from order_update ou
left join (
    select itemid, ordercode, sum(packages) ready 
    from daily_production 
    group by itemid, ordercode
) dp on dp.itemid = ou.itemid and dp.ordercode = ou.ordercode

【讨论】:

  • 非常感谢先生,这正是我想要的:)
猜你喜欢
  • 1970-01-01
  • 2020-12-08
  • 1970-01-01
  • 2010-12-08
  • 1970-01-01
  • 2017-11-14
  • 2016-03-06
  • 2021-02-22
  • 1970-01-01
相关资源
最近更新 更多