我有2张桌子
Id qty department
1 20 1
2 10 1
3 05 2
Id parent_id sub_qty
1 1 5
2 1 6
3 3 9
我想生成适合这种格式的行:
Id department qty sub_qty
1 1 30 11
2 2 05 09
我目前有以下SQL查询:
Select store.id,
store.department,
sum(store.qty),
sum(sub_qty)
from store
left join store_sub on store_sub.parent_id = store.id
Group by department
然而,它无效。
如何获得所需的输出?
答案 0 :(得分:1)
问题是{1} {id 1}在store
表中有两个相应的记录,这意味着store_sub
字段将对商店1出现两次。您需要对2个表进行求和分别在子查询中加入相加的版本:
qty
答案 1 :(得分:0)
Select store.id, store.department, sum(qty),
sum((select sum(sub_qty) from store_sub where parent_id = store.id group by parent_id )) as sub_qty
from store Group by department