两周后搜索我无法写这个查询请帮帮我
NOTE
TABLE 1 sum(quantity_box) group by id_p and id_w
TABLE 2 sum(quantity_box) group by id_p and id_w
then
TABLE1.sum(quantity_box)- TABLE2.sum(quantity_box) where id_p = id_p and id_w = id_w
表1)wherehouseproduct_add id = id_w
id | name
10 | warehouse1
20 | warehouse2
table2)wherehouse_products
id | id_w |id_p |quantity_box
1 | 10 | 2 | 10
2 | 10 | 2 | 50
3 | 20 | 3 | 100
4 | 20 | 1 | 20
5 | 20 | 1 | 10
6 | 10 | 1 | 10
7 | 10 | 3 | 10
table3)wherehouse_products_sell
id | id_w |id_p |quantity_box
1 | 10 | 2 | 50
2 | 20 | 3 | 30
3 | 20 | 1 | 20
table4)产品
id_p | product_name
1 | snack
2 | watebottle
3 | headphone
我希望输出像
id_w | id_p | product_name| total_quantity_box
10 | 1 | snack |10
10 | 2 | watebottle |10
10 | 3 | headphone |10
20 | 1 | snack |10
20 | 2 | watebottle |10
20 | 3 | headphone |70
答案 0 :(得分:0)
在子选择中单独计算每种类型的金额,并按照您的标准加入它们,然后在外部选择中进行计算
select wp.id_w,
wp.id_p,
wp.quantity - wps.quantity total_quantity_box
from
(select id_w,id_p,sum(quantity_box) quantity from wherehouse_products group by id_w,id_p) wp
join
(select id_w,id_p,sum(quantity_box) quantity from wherehouse_products_sell group by id_w,id_p) wps
using(id_w,id_p)