同一列中两个日期的DateDiff SQLite

时间:2019-03-24 22:38:35

标签: android sql sqlite join self-join

使用SQLite,我有这样的表:

ClockId          ProjectId           DateTime
-----------------------------------------------------------------
1                1                   1398/01/01 10:00:00
2                1                   1398/01/01 11:00:00
3                2                   1398/01/01 10:00:00
4                2                   1398/01/01 11:00:00
5                1                   1398/01/01 10:00:00
6                1                   1398/01/01 11:00:00
7                1                   1398/01/01 10:00:00
8                2                   1398/01/01 10:00:00
9                1                   1398/01/01 11:00:00
10               2                   1398/01/01 11:00:00

我需要这个输出:

ProjectId            Diff(minute)
------------------------------
1                    180
2                    120

准确地说,我需要两个这样的联接:

ClockId           ClockId
---------------------------
1                 2
3                 4
5                 6
7                 9
8                 10

我该怎么做?

我在sql而不是SQLite中尝试此代码:

select
    maintbl2.ProjectId,
    sum(maintbl2.diff) as sum
from (SELECT  
    ROW_NUMBER() OVER(ORDER BY mainTbl.ProjectId) AS Row#,
    mainTbl.ProjectId,
    DATEDIFF(minute, mainTbl.[DateTime], c1.[DateTime]) as diff
FROM [Clock] as c1
CROSS APPLY
        (SELECT TOP 1 * 
            FROM [Clock] as c2
            WHERE c1.ProjectId = c2.ProjectId and c1.DateTime > c2.DateTime
        ) mainTbl) maintbl2

但不能正常工作!

0 个答案:

没有答案