2010-05-29 68 views
0

我有兩個表作爲purchase_details和invoice_details如何根據鍵找到特定列的值之間的差異?

我想從這兩個表的數據中存儲每個產品的庫存/庫存。

結構purchase_details

'pid', 'int(10)' 
'product_id', 'int(10)' 
'quantity', 'float(8,2)' 
'amount', 'float(12,2)' 
'expiry_date', 'date' 

invoice_details結構。

'invoice_id', 'int(10) unsigned' 
'product_id', 'int(10) unsigned' 
'quantity', 'float(10,2)' 
'price', 'float(12,2)' 

我想計算剩餘股票 (從purchase_details的產品和數量)的總量 - (從invoice_details的產品和數量)

PRODUCT_ID是將相同的兩張表。

產品表由產品數據,並且該結構是

'id', 'int(10) unsigned' 
'cid', 'int(10) unsigned' 
'name', 'varchar(90)' 
'selling_price', 'float(10,2)' 
'mrp', 'float(10,2)' 
'reorder_level', 'bigint(20) unsigned' 

的invoice_details可以或可以不具有用於每PRODUCT_ID條目。

我該怎麼辦?

+0

任何答案,請您可以添加WHERE語句? – Vijay 2010-05-30 04:51:26

回答

0
select (sum(purchase_details.quantity) - sum(invoice_details.quantity)) as stock 
    from products 
    left outer join purchase_details 
    on products.product_id == purchase_details.product_id 
    left outer join invoice_details 
    on products.product_id = invoice_details.product_id 
    group by products.product_id 

這會給你的股票爲每個產品,如果你需要某些產品

select (sum(purchase_details.quantity) - sum(invoice_details.quantity)) as stock 
    from products 
    left outer join purchase_details 
    on products.product_id == purchase_details.product_id 
    left outer join invoice_details 
    on products.product_id = invoice_details.product_id 
    where products.product_id = 137 
    group by products.product_id 
+0

它返回錯誤的價值.. 我有136產品ID 7和20購買產品ID 8,12產品ID 7在發票,所以total應該124爲productid 7和20爲產品ID 8 ..但是其回調224和空 – Vijay 2010-05-29 12:23:29

+0

,因爲您需要先調用產品表,我會修改語句看看 – 2010-05-29 12:37:26

+0

沒有它仍然不起作用 我的產品表具有唯一的ID,但product_id可能會在purchase_details和invoice_details中重複。 – Vijay 2010-05-29 13:38:27

1

這是我的新答案,已經在sqlserver上測試過了。我不知道關於MySQL

select pro.id, SUM(pro.quantity - inv.quantity) 
from (select sum(p.quantity) as quantity, p.id as id from product p group by p.id) as pro, 
    (select sum(i.quantity) as quantity, i.id as id from invoice i group by i.id) as inv 
where inv.id = pro.id 
group by pro.id; 
+0

它不工作..我有多個產品在產品表中。 product_id將在purchase_details和invoice_details表中重複。我想爲每種產品計算庫存 – Vijay 2010-05-29 13:52:40

+0

uhm,這意味着,您想列出每個產品ID的庫存(差異)? – vodkhang 2010-05-29 13:56:57

+0

這就是我想要的.. – Vijay 2010-05-29 14:01:55

相關問題