Tsql datetime设置除了操作

时间:2012-11-15 17:03:49

标签: sql-server tsql datetime set-difference

我有一个“检测到的状态”表,其中包含日期时间对,以及与日期时间对偶的“预期存在”表... 我想知道什么时候我预期存在,但没有...我认为这与日期时间设置不同(在tsql除了操作数),但我不知道如何用sql解决。

如果我不清楚的一个例子:

    CREATE TABLE [dbo].[DetectedPresence](
        [entrance] [datetime] NULL,
        [exit] [datetime] NULL
    )

    CREATE TABLE [dbo].[ExpectedPresence](
        [entrance] [datetime] NULL,
        [exit] [datetime] NULL
    )

INSERT INTO ExpectedPresence VALUES ('2012-11-16 08.15','2012-11-16 12.00')
INSERT INTO ExpectedPresence VALUES ('2012-11-16 17.00','2012-11-16 18.00')
INSERT INTO DetectedPresence VALUES ('2012-11-16 08.00','2012-11-16 12.00')
INSERT INTO DetectedPresence VALUES ('2012-11-16 15.00','2012-11-16 18.00')

ExpectedPresence值:

entrance               exit
2012-11-16 08.00       2012-11-16 12.00
2012-11-16 15.00       2012-11-16 18.00

DetectedPresence值:

entrance               exit
2012-11-16 08.15       2012-11-16 12.00
2012-11-16 15.00       2012-11-16 17.00

我希望日期时间设置不同(差距):

2012-11-16 08.00       2012-11-16 08.15
2012-11-16 17.00       2012-11-16 18.00
你能帮帮我吗?谢谢。

1 个答案:

答案 0 :(得分:0)

的内容
case when detectedStart > expectedStart then 
   expectedStart + '-' + detectedStart 
else null end as startDiff,
case when detectedEnd < expectedEnd then 
   detectedEnd + '-' + expectedEnd 
else null end as endDiff

    insert into difference (expectedStart, detectedStart)
    Select
        expectedStart,detectedStart 
    from 
        ExpectedPresence e inner join
        DetectedPresence d on
        e.staffID = d.staffID
    where
       detectedStart > expectedStart;

    insert into difference (expectedEnd, detectedEnd)
    Select  
        expectedEnd,detectedEnd 
    from 
        ExpectedPresence e inner join
        DetectedPresence d on
        e.staffID = d.staffID
    where
        detectedEnd < expectedEnd