2013-05-10 100 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)