2013-05-10 62 views
0

我需要你的幫助。我有這個代碼來查詢我的機器,這些機器在租賃,庫存和我的網點上。但這隻適用於我輸入一個itemID。這意味着它一次只能查詢一個項目。我需要查詢租賃和網點上的機器數量,與現有庫存數量平行。謝謝 !計數表上的項目

`alter procedure GetItemsForQueries 
@itemID varchar(15) 
as begin 
select i.ItemName, m.MachineModel, i.SellingPrice, i.QuantityOnHand, 
(select COUNT(*) from ClientMachine where AcquisitionType = 'Rental' and ItemID = @itemID) as 'Quantity on Rentals', 
(select COUNT(*) from OutletMachine where ItemID = @itemID) as 'Quantity on Outlets' 
from Item i inner join Machine m on (m.ItemID = i.ItemID) 
where i.ItemID = @itemID 
end` 

回答

0

兩個子查詢應該這樣做 - 這樣的事情...

簡而言之,發現所有的機器,加入針對其發現的計數ID的子查詢那租金和對另一子查詢再次加入該發現每口機的個性化......

select m.itemid, 
     ifnull(ccount,0) as rental_count, 
     ifnull(ocount,0) as outlet_count 
from Machine m 
left join (select itemid, 
      count(*) as ccount 
      from ClientMachine 
      where AcquisitionType = 'Rental' group by ItemID) a1 on (a1.itemid=m.itemid) 
left join (select itemid, 
      count(*) as ocount 
      from OutletMachine group by ItemID) a2 on (a2.itemid=m.itemid) 
+0

只是增加了一些代碼到你的答案,而這一次似乎是最近的我需要什麼。謝謝 ! – 2013-05-10 17:28:02

+0

謝謝!幾乎每個人都做了同樣的事情,這是一個非常常見的模式,在編寫查詢時你會反覆使用。 – Stephen 2013-05-10 17:29:38

0

我的頭頂部(也有一些語法錯誤,但邏輯是存在的)

select i.ItemId, i.ItemName, m.MachineModel, i.SellingPrice, i.QuantityOnHand, rental.rentalCount, outlet.outletCount 
from Item i 
left join (select ItemId, count(*) as 'rentalCount' from ClientMachine Where AcquisitionType = 'Rental' group by ItemId) rental on rental.ItemId = i.ItemId 
left join (select ItemId, count(*) as 'outletCount' from OutletMachine group by ItemId) outlet on outlet.ItemId = i.ItemId 
inner join Machine m on (m.ItemID = i.ItemID) 
0

檢查這個代碼:

select i.ItemName, 
     m.MachineModel, 
     i.SellingPrice, 
     i.QuantityOnHand, 
     (select COUNT(*) from ClientMachine where AcquisitionType = 'Rental' and ItemID =   i.ItemID) as 'Quantity on Rentals', 
     (select COUNT(*) from OutletMachine where ItemID = i.ItemID) as 'Quantity on Outlets' 
from Item i inner join Machine m on (m.ItemID = i.ItemID)