2015-10-01 59 views
0

尋找MaxDate,它的最近日期和之間的時間間隔。的MAXDATE和最近,我還需要爲每個的數量,所以我還可以找到如下的間隔MS Access最大日期和最近日期以及它們各自的數量

表「tblITEM_InventoryCount」的結構是:

ITEM_NO盤點日期數量

001 08 /二千○十五分之二十九12

001 2015年8月15日17

001 2015年7月15日19

貨號001

MAX(CountDate)2015年8月29日

PriorCountDate 2015年8月15日

間隔天數(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。

我需要最大或最後countdate和它的數量和先前countdate和它的數量。

任何幫助將不勝感激。

回答

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 ; 
+0

謝謝@Sagar但將此代碼粘貼到一個查詢的SQL視圖後,我仍然有困難。 – kduncan

+0

@kduncan,你能否提一下哪些錯誤即將到來? –