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
4

3 回答 3

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)
于 2013-05-10T17:20:56.467 回答
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)
于 2013-05-10T17:24:00.727 回答
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)
于 2013-05-10T17:26:19.817 回答