1

我有多个应用程序,每个应用程序都有唯一的应用程序 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)

希望我清楚。我怎样才能做到这一点,我尝试了 Ranking 和 Row_Number。但我可能在某个地方错了。我正在使用 SQL Server,但无法使用 LAG()

4

2 回答 2

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

我仍然认为您应该在 UI 中执行此操作。

于 2013-02-01T03:45:24.950 回答
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

这是小提琴

祝你好运。

于 2013-02-01T03:59:48.220 回答