我有一张表,其中有一列日期,我想找到它们之间的区别。我已经能够找到一个答案,让我得到两个日期之间的差异,但找不到任何可以让我区分每个客户的几条记录。
我的数据如下所示:
Customer Pstng_Date
Henry 05\01\2014
Henry 10\01\2014
Henry 15\01/2014
Williams 07\01/2014
Williams 15\01\2014
我一直在使用下面的代码来计算威廉姆斯的例子,但不能让它工作,以便计算所有亨利的例子。我想看到的是:
Customer Pstng_Date Days_Between
Henry 05\01\2014 0
Henry 10\01\2014 5
Henry 15\01/2014 5
Williams 07\01/2014 0
Williams 15\01\2014 8
我一直在使用以下代码来计算两个记录之间的差异。
SELECT AllDays.ID, AllDays.Customer, AllDays.Pstng_Date, AllDays.NextDate, DateDiff("d",[Pstng_Date],[NextDate]) AS Days
FROM (SELECT ID, Customer, Pstng_Date,
( SELECT Min(Pstng_Date)
FROM SAPData T2
WHERE T2.Pstng_Date > T1.Pstng_Date
) AS NextDate
FROM SAPData T1
) AS AllDays;
答案 0 :(得分:3)
更改相关子查询,使其返回Pstng_Date
T1.Customer
值的最大值
此查询返回了在Access 2007中使用示例数据进行测试时所需的内容。
SELECT
AllDays.Customer,
AllDays.Pstng_Date,
Nz(DateDiff("d",[PreviousDate],[Pstng_Date]), 0) AS Days_Between
FROM
(
SELECT
Customer,
Pstng_Date,
(
SELECT Max(Pstng_Date)
FROM SAPData AS T2
WHERE
T2.Customer = T1.Customer
AND T2.Pstng_Date < T1.Pstng_Date
) AS PreviousDate
FROM SAPData AS T1
) AS AllDays;
如果您将从Access会话外部运行查询,则Nz()
功能将不可用。在这种情况下,您可以使用IIf()
表达式。
IIf([PreviousDate] Is Null, 0, DateDiff("d",[PreviousDate],[Pstng_Date]))
答案 1 :(得分:1)
当我对此感到恐惧时,我得到的错误如下: 找不到任何一列&#34;游戏中时光倒流&#34;或用户定义的函数或聚合&#34; Timelapse.start_date_time&#34;,或名称不明确。
我重新推荐了AllDays&#39;随着&#39;游戏中时光倒流&#39;
SELECT
Timelapse.[request_id],
--Timelapse.[task_code],
Timelapse.[start_date_time]-->getting error at this column
(DateDiff(day,[PreviousDate],[start_date_time]), 0) AS Days_Between
FROM
(
SELECT
[request_id],[task_code],
[start_date_time],
(
SELECT Max([start_date_time])
FROM [Monitor247].[dbo].[request_task] AS T2
WHERE
T2.[request_id] = T1.[request_id]
AND T2.[start_date_time] < T1.[start_date_time]
) AS PreviousDate
FROM [Monitor247].[dbo].[request_task] AS T1
) AS Timelapse;