在查询中聚合子查询

时间:2014-08-08 21:42:59

标签: sql sql-server tsql

我目前正致力于汇总" OUT"的总和数量。和" OUT + IN"。 当前查询如下:

Select 
a.Date
,a.DepartmentID

from 
(Select
dris.Date
,dris.RentalItemKey 
,dris.WarehouseKey
,ISNULL((Select TOP 1 dris.Date where OutQty=1 order by Date DESC),(Select ri.ReceiveDate from RentalItem ri where ri.RentalItemKey=dris.RentalItemKey)) as LastOutDate
,(Select d.DepartmentKey from Department d where d.Department=i.Department)as DepartmentID
, (CASE WHEN OutQty=1 OR (RepairQty=1 AND RentedQty=1) THEN 'IN' ELSE 'OUT' END) as Status

from DailyRentalItemStatus dris 
inner join Inventory i on i.InventoryKey=dris.InventoryKey
where dris.Date='2014-08-02'
and i.ICode='3223700'
and i.Classification IN ('ITEM', 'ACCESSORY')
and i.AvailFor='RENT'
and i.AvailFrom='WAREHOUSE'
and dris.Warehouse='TORONTO')a

我希望结果如下:

Date       WarehouseID  DepartmentID    ICode   Owned   NotRedundant    Out
2014-08-02    001T         A00G        3223700   30         30          19

拥有的地方是状态为" OUT + IN",out的项目是" OUT"而且不是冗余,因为过去的日期是在距离日期的最后2年内。

非常感谢帮助。

1 个答案:

答案 0 :(得分:0)

认为这接近你正在寻找的东西。您的非冗余描述很难理解。你比较哪个日期。虽然OUT可以使用相同的技巧。 我的查询还假设您总是有一个部门连接到库存表,并且总是有一个rentalitem.receivedate。

;WITH LastOut as 
(Select Max(Date) as LastOutDate, rentalItemKey
from DailyRentalItemStatus
WHERE OutQty=1
)
Select
dris.Date
,dris.WarehouseKey as WarehouseID 
,d.DepartmentKey as DepartmentID
, i.Icode
--,ISNULL((Select TOP 1 dris.Date where OutQty=1 order by Date DESC),(Select ri.ReceiveDate from RentalItem ri where ri.RentalItemKey=dris.RentalItemKey)) as LastOutDate
, Count(1) as Owned
, Sum(CASE WHEN NOT (OutQty=1 OR (RepairQty=1 AND RentedQty=1)) THEN 1 ELSE 0 END) as OUT
, Sum(CASE WHEN DateAdd(yy, 2,dris.[date]) >= ISNULL(lastout.lastoutdate, ri.ReceiveDate) then 1 else 0 end) as NonRedundent
from DailyRentalItemStatus dris 
inner join Inventory i on i.InventoryKey=dris.InventoryKey 
INNER JOIN Department d ON d.Department=i.Department
INNER JOIN RentalItem ri ON ri.RentalItemKey=dris.RentalItemKey 
LEFT OUTER JOIN LastOUT ON LastOut.rentalItemKey=dris.RentalItemKey
where dris.Date='2014-08-02'
and i.ICode='3223700'
and i.Classification IN ('ITEM', 'ACCESSORY')
and i.AvailFor='RENT'
and i.AvailFrom='WAREHOUSE'
and dris.Warehouse='TORONTO'
Group BY dris.Date, d.DepartmentKey, Dris.WarehouseKey , i.icode