寻找MaxDate,它的最新日期和间隔。在MaxDate和最近的,我还需要每个的数量,所以我也可以找到间隔
表“tblITEM_InventoryCount”结构如下:
Item_No计数日期数量
001 08/29/2015 12
001 08/15/2015 17
001 07/15/2015 19
项目编号001
Max(CountDate)2015年8月29日
PriorCountDate 08/15/2015
间隔天数(MaxDate-RecentDate)14
MaxDate数量12
PriorCountDate数量17
区间数量(17-12)5
目前使用查询查找每个ITEM_NO的最后两个计数日期
SELECT tblITEM_InventoryCount.ITEM_NO, tblITEM_InventoryCount.Quantity, tblITEM_InventoryCount.CountDate
FROM tblITEM_InventoryCount
WHERE (((tblITEM_InventoryCount.CountDate)>=NthInGroup([tblITEM_InventoryCount].[ITEM_NO],2)))
ORDER BY tblITEM_InventoryCount.ITEM_NO, tblITEM_InventoryCount.CountDate DESC;
然后我使用第二个查询来计算我的数据:
SELECT qryLAST2_InventoryCount_TRANSACTIONS.ITEM_NO, qryLAST2_InventoryCount_TRANSACTIONS.CountDate, (SELECT MAX([CountDate]) FROM [qryLAST2_InventoryCount_TRANSACTIONS] AS [Old Orders] WHERE [Old Orders].[CountDate] < [qryLAST2_InventoryCount_TRANSACTIONS].[CountDate] AND [Old Orders].[ITEM_NO] = [qryLAST2_InventoryCount_TRANSACTIONS].[ITEM_NO]) AS PriorCountDate, [CountDate]-[PriorCountDate] AS DaysInterval, qryLAST2_InventoryCount_TRANSACTIONS.Quantity, (SELECT Last([Quantity]) FROM [qryLAST2_InventoryCount_TRANSACTIONS] AS [OldCount] WHERE [OldCount].[Quantity] < [qryLAST2_InventoryCount_TRANSACTIONS].[Quantity] AND [OldCount].[ITEM_NO] = [qryLAST2_InventoryCount_TRANSACTIONS].[ITEM_NO]) AS PriorQuantity, [Quantity]-[PriorQuantity] AS QuantityInterval, [QuantityInterval]*30/[DaysInterval] AS [Usage]
FROM qryLAST2_InventoryCount_TRANSACTIONS
GROUP BY qryLAST2_InventoryCount_TRANSACTIONS.ITEM_NO, qryLAST2_InventoryCount_TRANSACTIONS.CountDate, qryLAST2_InventoryCount_TRANSACTIONS.Quantity
ORDER BY qryLAST2_InventoryCount_TRANSACTIONS.ITEM_NO, qryLAST2_InventoryCount_TRANSACTIONS.CountDate DESC;
我没有得到我需要的结果。查询返回每个项目的两条记录行及其最大或最后一个countdate,前一个countdate,intervaldays,qty,last qty和interval。
我需要max或last countdate及其数量计数和之前的countdate及其数量。
非常感谢任何帮助。
答案 0 :(得分:0)
试试这个:
select
tab.item_no,
tab.Max_Date,
tab.PriorCountDate,
DateDiff ("d", tab.Max_Date, tab.PriorCountDate) as IntervalDays,
tab.MaxDateQty,
tab.PriorCountDateQty,
( tab.MaxDateQty-tab.PriorCountDateQty) as IntervalQty,
from
( select
temp1.item_no as item_no,
temp1.m as Max_Date,
(select MAX(count_date) from tblITEM_InventoryCount where count_date <> temp1.m ) as PriorCountDate,
temp1.q as MaxDateQty,
(select MAX(Qty) from tblITEM_InventoryCount where Qty <> temp1.q) as PriorCountDateQty,
from
( select item_no as i, Qty as q, MAX(count_date) as m
group by item_no, Qty ) as temp1
inner join
tblITEM_InventoryCount as temp2
on
temp1.item_no = temp2.item_no
)
as tab ;