[英]Mysql Database: Joins sums and group by
我有两个表 OrderUpdate 和 DailyProduction
订单_更新
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
如果我正确地跟随您,您可以使用聚合查询left join
表order_update
,该查询汇总表order_update
中每个(itemid, ordercode)
的daily_production
:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.