我有一个包含以下结构的表
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)
基本上我想要做的是有一个访问查询来计算连续记录的日期差异但是对于相同的帐号 预期的结果将是!!
1001 10/9/2011 - 12/9/2011 2 days
1001 12/9/2011 - 20/9/2011 8 days
1001 20/9/2011 NA
基本上我想要做的是有一个访问查询来计算连续记录的日期差异但是对于相同的帐号,在上面的示例中将是1001.(日期不必显示在结果)
我使用access 2003。
答案 0 :(得分:49)
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
答案 1 :(得分:3)
如果需要,您可以为帐号添加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;
答案 2 :(得分:0)
试试这个:
select [Account Number], DATEDIFF(DD, min(date), max(date)) as dif
from your_table
group by [Account Number]
答案 3 :(得分:0)
GarethD的回答对我很有帮助。
仅供参考:当您需要ORDER BY子句时,请在根目录中的SELECT查询结束时使用它。
SELECT ConsignorID,
DateRequired StartDate,
NextDate,
DATEDIFF("D", DateRequired, NextDate)
FROM ( SELECT ConsignorID,
DateRequired,
(SELECT MIN(DateRequired)
FROM "TABLENAME" T2
WHERE T2.DateRequired > T1.DateRequired
) AS NextDate
FROM "TABLENAME" T1
) AS T
ORD BY T.DateRequired ASC
答案 4 :(得分:0)
您还可以使用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
答案 5 :(得分:-1)
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