获取已连接表的DateTime差异的总和

时间:2013-09-13 15:06:00

标签: sql sql-server sql-server-2008

我有2个表,一个存储时钟,另一个存储ClockInLogs.TimeIn和TimeOut之间的中断。每个时钟的时间总会超过1次。

ClockInLogs - 
ID - int
TimeIn - DateTime
TimeOut - DateTime


Breaks - 
CID - Int (joined to ClockInLogs.ID)
TimeIn - DateTime
TimeOut - DateTime

在我的SQL查询中,我需要检索每个Clock In的break列中的总小时数。到目前为止我有 -

SELECT
    C.ID,
    C.ClockDateTimeIn as 'Date',
    DATENAME(dw, C.ClockDateTimeIn) as 'DayOfWeek',
    C.UserID,
    C.ClockDateTimeIn as 'ClockInTime',
    C.ClockDateTimeOut as 'ClockOutTime',
    DATEDIFF(minute, ClockDateTimeIn, ClockDateTimeOut) as 'Att'
FROM clockinlogs C
INNER JOIN breaks b on C.ID = b.CID
INNER JOIN Users u on C.UserID = u.ID

所需的下一栏是休息时间内的总小时数。基本上,对于每个Break.TimeIn和Break.TimeOut,计算出小时数的差异,然后添加每个分解。

我希望这是有道理的!

2 个答案:

答案 0 :(得分:0)

希望这有效:

    SELECT C.ID
           ,C.ClockDateTimeIn as 'Date' 
           ,DATENAME(dw, C.ClockDateTimeIn) as 'DayOfWeek'
           ,C.UserID
           ,C.ClockDateTimeIn as 'ClockInTime'
           ,C.ClockDateTimeOut as 'ClockOutTime'
           ,SUM(convert(time,(b.TimeOut - b.TimeIn))) Att_time
           ,SUM(DATEDIFF(MI, ClockDateTimeIn, ClockDateTimeOut)) Att_minute
           ,SUM(DATEDIFF(HH, ClockDateTimeIn, ClockDateTimeOut)) Att_hour
      FROM clockinlogs C
      JOIN breaks b 
        ON C.ID = b.CID
      JOIN Users u 
        ON CID=ID
  GROUP BY C.ID
           ,C.UserID
           ,C.ClockDateTimeIn
           ,C.ClockDateTimeOut

Att_time将brekatime转换为数据类型时间

为什么加入用户?要检索名称?

答案 1 :(得分:0)

我对你最后一次内部联接感到有点困惑,因为你没有在查询中使用users表中的任何字段,除非你当然试图为那些不存在的用户过滤掉clockinlogs。用户表但是有可能吗?如果不是,它只会增加您不需要的查询开销。

无论如何,我无论如何都不是SQL专家,我可以说这不是最有效的查询,但我想这可行,尝试将其作为查询的最后一栏插入...

(SELECT
    SUM(break)
 FROM (SELECT
           DATEDIFF(minute, BreakTimeIn, BreakTimeOut) AS break
       FROM Breaks
       WHERE CID = C.ID)
 ) AS 'breaks'

您的整个查询应如下所示:

SELECT
    C.ID,
    C.ClockDateTimeIn as 'Date',
    DATENAME(dw, C.ClockDateTimeIn) as 'DayOfWeek',
    C.UserID,
    C.ClockDateTimeIn as 'ClockInTime',
    C.ClockDateTimeOut as 'ClockOutTime',
    DATEDIFF(minute, ClockDateTimeIn, ClockDateTimeOut) as 'Att',
    (SELECT
        SUM(break)
     FROM (SELECT
               DATEDIFF(minute, BreakTimeIn, BreakTimeOut) AS break
           FROM Breaks
           WHERE CID = C.ID)
     ) AS 'breaks'
FROM clockinlogs C
INNER JOIN breaks b on C.ID = b.CID