0

I have 2 tables, one stored clocking in times and the other stores breaks taken between the ClockInLogs.TimeIn and TimeOut. There is always going to be more than 1 break for each clockintime.

ClockInLogs - 
ID - int
TimeIn - DateTime
TimeOut - DateTime


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

In my SQL query, I need to retrieve the total number of hours in the breaks column for each Clock In. So far I have -

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

The next column needed is a total number of hours within the breaks. Basically, for each Break.TimeIn and Break.TimeOut, work out the difference in hours, then add each break up.

I hope this makes sense!

4

2 回答 2

0

hope this works:

    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 converts the brekatime to datatype time

Why do You join to Users? To retrieve a name?

于 2013-09-13T15:17:50.673 回答
0

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

无论如何,我无论如何都不是 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
于 2013-09-13T15:26:47.413 回答