我有一个表,结构如下
ID Account Number Date
1 1001 10/9/2011 (dd/mm/yyyy)
2 2001 1/9/2011 (dd/mm/yyyy)
3 2001 3/9/2011 (dd/mm/yyyy)
4 1001 12/9/2011 (dd/mm/yyyy)
5 3001 18/9/2011 (dd/mm/yyyy)
6 1001 20/9/2011 (dd/mm/yyyy)基本上我想做的是有一个access查询,它计算连续记录的日期差异,但对于相同的账号,预期的结果将是!!
1001 10/9/2011 - 12/9/2011 2 days
1001 12/9/2011 - 20/9/2011 8 days
1001 20/9/2011 NA基本上,我想做的是有一个access查询,它计算连续记录的日期差异,但对于相同的账号,在上面的例子中将是1001。(日期不必显示在结果中)
我使用access 2003。
发布于 2012-04-03 22:23:07
SELECT T1.ID,
T1.AccountNumber,
T1.Date,
MIN(T2.Date) AS Date2,
DATEDIFF("D", T1.Date, MIN(T2.Date)) AS DaysDiff
FROM YourTable T1
LEFT JOIN YourTable T2
ON T1.AccountNumber = T2.Accountnumber
AND T2.Date > T1.Date
GROUP BY T1.ID, T1.AccountNumber, T1.Date;或
SELECT ID,
AccountNumber,
Date,
NextDate,
DATEDIFF("D", Date, NextDate)
FROM ( SELECT ID,
AccountNumber,
Date,
( SELECT MIN(Date)
FROM YourTable T2
WHERE T2.Accountnumber = T1.AccountNumber
AND T2.Date > T1.Date
) AS NextDate
FROM YourTable T1
) AS T发布于 2019-05-23 19:38:36
您还可以使用LAG分析函数来获得所需的结果,如下所示:
假设下面是您的输入表:
id account_number account_date
1 1001 9/10/2011
2 2001 9/1/2011
3 2001 9/3/2011
4 1001 9/12/2011
5 3001 9/18/2011
6 1001 9/20/2011
select id,account_number,account_date,
datediff(day,lag(account_date,1) over (partition by account_number order by account_date asc),account_date)
as day_diffrence
from yourtable;以下是您的输出:
id account_number account_date day_diffrence
1 1001 9/10/2011 NULL
4 1001 9/12/2011 2
6 1001 9/20/2011 8
2 2001 9/1/2011 NULL
3 2001 9/3/2011 2
5 3001 9/18/2011 NULL发布于 2012-04-03 22:16:30
如果需要,您可以为帐号添加WHERE语句。您的表名为t4
SELECT
t4.ID,
t4.AccountNumber,
t4.AcDate,
(SELECT TOP 1 AcDate
FROM t4 b
WHERE b.AccountNumber=t4.AccountNumber And b.AcDate>t4.AcDate
ORDER BY AcDate DESC, ID) AS NextDate,
[NextDate]-[AcDate] AS Diff
FROM t4
ORDER BY t4.AcDate;https://stackoverflow.com/questions/9994862
复制相似问题