2017-02-22 54 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