2011-10-30 118 views
-2

我必須在我們的數據庫中運行一個sql命令,我無法弄清楚這一點。以下是需要的:棘手的SQL查詢

「顯示已向我們出售過多件物品的供應商的名稱,列出供應商,物品和訂購次數假設供應商在12月1日售出了物品240中的8件和12月30日的項目240中的12個;這被計爲項目240(不是20)的兩個總訂單。「

Here is our DB 這是我到目前爲止。我知道這是超級錯誤,但我不知道如何做對。

select v.VENDORID, poi.PARTNUM, count (po.PONUM) 
    from vendor v, purchaseorder po, poitems poi 
    where v.VENDORID=po.VENDORID and po.PONUM=poi.PONUM 

任何幫助將不勝感激!非常感謝!

+0

這是功課? –

+4

聞起來像功課很長的路要走。 – bos

+1

供應商和部件不應該連接嗎?我的意思是賣家不賣這個零件嗎? – abruski

回答

2

您在查詢中缺少HAVING和GROUP BY。查詢應該是這樣的:

SELECT v.name, poi.PARTNUM, count (po.PONUM) 
FROM vendor v 
LEFT JOIN purchaseorder po ON (v.vendorid=po.vendorid) 
LEFT JOIN poitems poi ON (po.PONUM=poi.PONUM) 
WHERE poi.PARTNUM IS NOT NULL 
GROUP BY (v.vendorID, poi.partnum) 
HAVING COUNT(po.ponum) > 1 
0

希望此查詢適用於你:

Select name 
,description 
,count(quantity) 
from parts p 
,(Select a.vendorid,name,ponum from purchaseorders a, 
(Select vendorid,count(*) from purchaseorders 
--All vendors who have purchased more then once 
group by vendorid having count(vendorid)>1) b 
,vendor v 
where a.vendorid=b.vendorid 
and v.vendorid=a.vendorid) o 
,(select vendorid,o.ponum,partnum,count(partnum) quantity 
--the quantity of orders  placed 
from poitems p ,purchaseorders o 
where o.ponum=p.ponum 
group by vendorid,partnum,o.ponum) i 
where i.vendorid=o.vendorid 
and p.partnum=i.partnum 
and i.ponum=o.ponum 
group by name,description