gpt4 book ai didi

mysql - SQL SELECT SUM 从两个表和分组依据

转载 作者:行者123 更新时间:2023-11-29 01:02:47 27 4
gpt4 key购买 nike

我有两个表(PO 和 GRN)。我想得到:[这就是我正在做的:][1] http://sqlfiddle.com/#!9/db000/2

我得到了这些结果(错误的 po_qty 、 GRN_qty 和 GRN_balance )。

我期待的是:

| Item | PONO | po_qty | GRN_qty | GRN_balance |
|------|------|--------|---------|-------------|
| A | po1 | 70 | 65 | 5 |
| B | po1 | 50 | 0 | 50 |
| C | po2 | 10 | 5 | 5 |
| D | po3 | 20 | 0 | 20 |
| A | po4 | 15 | 10 | 5 |

最佳答案

这里有一个方法

select 
p.Item,
p.PONO,
sum(p.Qty) as po_qty,
coalesce(g.GRN_qty,0) ,
sum(p.Qty) - coalesce(g.GRN_qty,0) as GRN_balance
from PO p
left join (
select PONO,Item,sum(Qty) as GRN_qty from GRN
group by PONO,Item
)g
on g.PONO = p.PONO and g.Item = p.Item
group by p.Item,p.PONO
order by p.PONO

http://sqlfiddle.com/#!9/db000/30

关于mysql - SQL SELECT SUM 从两个表和分组依据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30932505/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com