2017-02-22 59 views
0

我尝试混合两种查询,PostgreSQL连接两个查询的PostgreSQL

select stock_quant.product_id as prod_id, product_product.name_template as name ,sum(stock_quant.qty) as qty_quant 
from stock_quant 
join product_product on stock_quant.product_id = product_product.id 
join stock_location on stock_quant.location_id = stock_location.id 
where stock_location.usage in ('internal','transit') 
group by stock_quant.product_id, product_product.name_template 
order by stock_quant.product_id 

这一个让我产品和用量数据在表stock_quant ,第二个查询得到我quntity的总和在其他表“stock_history”

select stock_history.product_id as prod_id,product_product.name_template as name , sum(stock_history.quantity) as qty_history 
from stock_history 
join product_product on stock_history.product_id = product_product.id 
group by stock_history.product_id,name 
order by stock_history.product_id 

好,什么即时试图做的是只显示这两者之和相等的同一种产品的产品OFC 日Thnx我真的很感激一些解释

+0

你们更多的解释好了,如果你会提供的表的模式,那本来是好的。 –

回答

0

很好的答案是:

select stock_quant.product_id as prod_id, product_product.name_template as name ,sum(stock_quant.qty) as qty_quant 
from stock_quant 
join product_product on stock_quant.product_id = product_product.id 
join stock_location on stock_quant.location_id = stock_location.id 
where stock_location.usage in ('internal','transit') 
group by stock_quant.product_id, product_product.name_template 
having sum(stock_quant.qty) != (
    select sum(stock_history.quantity) as qty_history 
    from stock_history 
    where stock_quant.product_id = stock_history.product_id) 
order by stock_quant.product_id 

目前,我在工作中,我将提供后,如果需要 日Thnx