我有多个应用程序,每个应用程序都有唯一的应用程序ID,每个应用程序都有一个存储在表格中的日志。我想知道如何计算日期差异 例如:
AppID Start Loggedon change
A1 08/07/2010 08/09/2010 Xchange
A1 08/07/2010 08/20/2010 Ychange
A1 08/07/2010 08/30/2010 Zchange
A2 07/07/2010 07/13/2010 Ychange
A3 09/07/2010 09/09/2010 Xchange
所以我想要值
Difference
2 (Difference between the application start date and 1st loggedon date)
11 (difference between 08/20 and 08/09, the prior row because AppID stayed the same)
10 (difference between 08/30 and 08/20, the prior row because AppID stayed the same)
6 (Difference between the application start date and 1st loggedon date)
2 (Difference between the application start date and 1st loggedon date)
希望我很清楚。我怎样才能实现这一点,我尝试了排名和Row_Number。但我可能在某处错了。我使用的是SQL Server,无法使用LAG()
答案 0 :(得分:1)
好的,这会奏效。享受。
现在测试了!谢谢sgeddes - http://sqlfiddle.com/#!3/e4d28/19
WITH tableNumbered AS
(
SELECT *,
ROW_NUMBER() OVER (PARTITION BY AppID ORDER BY AppID, Start , Loggedon ) AS row
FROM Apps
)
SELECT t.*,
CASE WHEN t2.row IS NULL THEN DATEDIFF(day,t.Start,t.LoggedOn)
ELSE DATEDIFF(day,t2.LoggedOn,t.Loggedon)
END as diff
FROM tableNumbered t
LEFT JOIN tableNumbered t2 ON t.AppID = t2.AppID AND t2.row+1 = t.row
我仍然认为你应该在用户界面中这样做。
答案 1 :(得分:1)
@Hogan有正确的方法,但由于某种原因,我无法让它完全运作。这是一个微小的变化,似乎产生了正确的结果 - 但是,请接受@Hogan的回答,因为他打败了我:)
WITH cte AS (
SELECT AppId, Start, LoggedOn,
ROW_NUMBER() OVER (ORDER BY AppId) rn
FROM Apps
)
SELECT c.AppId,
CASE
WHEN c2.RN IS NULL
THEN DATEDIFF(day,c.start,c.Loggedon)
ELSE
DATEDIFF(day,c2.Loggedon,c.Loggedon)
END as TimeWanted
FROM cte c
LEFT JOIN cte c2 on c.AppId = c2.AppId
AND c.rn = c2.rn + 1
这是Fiddle。
祝你好运。