计算表格上的项目

时间:2013-05-10 17:12:44

标签: sql

我需要你的帮助。我有这个代码来查询我的机器,这些机器出租,库存和我的网点,但这只有在我输入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

3 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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)

答案 2 :(得分: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)