Sqlserver
 sql >> Baza danych >  >> RDS >> Sqlserver

Oblicz różnicę czasu dla obecności

Wypróbuj ten -

DECLARE @temp TABLE
(
    UserID INT,
    Checktime DATETIME,
    CheckStatus CHAR(1)
)

INSERT INTO @temp (UserID, Checktime, CheckStatus)
VALUES 
    (3175, '20131222 07:02:10.000', 'I'),
    (3175, '20131222 13:01:01.000', 'O'),
    (3175, '20131222 13:49:54.000', 'I'),
    (3175, '20131222 13:49:55.000', 'I'),
    (3175, '20131222 15:58:42.000', 'O'),
    (3175, '20131223 06:02:58.000', 'I'),
    (3175, '20131223 14:00:29.000', 'O'),
    (3175, '20131224 05:17:09.000', 'I'),
    (3175, '20131224 12:34:25.000', 'O'),
    (3175, '20131224 12:34:26.000', 'O')

SELECT 
      t.UserID
    , [Date] = DATEADD(dd, 0, DATEDIFF(dd, 0, t.CheckIn))
    , CheckIn = CONVERT(VARCHAR(10), t.CheckIn, 108)
    , CheckOut = CONVERT(VARCHAR(10), t.CheckOut, 108)
    , [Hours] = CAST(DATEDIFF(MINUTE, t.CheckIn, t.CheckOut) / 60. AS DECIMAL(10,2))
FROM (
    SELECT 
          t.UserID
        , CheckIn = t.Checktime
        , CheckOut = r.Checktime
        , RowNum = ROW_NUMBER() OVER (PARTITION BY t.UserID, r.Checktime ORDER BY 1/0)
    FROM @temp t
    OUTER APPLY (
        SELECT TOP 1 *
        FROM @temp t2
        WHERE t2.UserID = t.UserID
            AND t2.Checktime > t.Checktime
            AND DATEADD(dd, 0, DATEDIFF(dd, 0, t.Checktime)) = DATEADD(dd, 0, DATEDIFF(dd, 0, t2.Checktime))
            AND t2.CheckStatus = 'O'
        ORDER BY t2.Checktime
    ) r
    WHERE t.CheckStatus = 'I'
) t
WHERE t.RowNum = 1

Wyjście -

UserID      Date                    CheckIn    CheckOut   Hours
----------- ----------------------- ---------- ---------- --------
3175        2013-12-22 00:00:00.000 07:02:10   13:01:01   5.98
3175        2013-12-22 00:00:00.000 13:49:54   15:58:42   2.15
3175        2013-12-23 00:00:00.000 06:02:58   14:00:29   7.97
3175        2013-12-24 00:00:00.000 05:17:09   12:34:25   7.28


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Jak CAST() działa w SQL Server

  2. SQL Server dodaje automatyczny klucz podstawowy do istniejącej tabeli

  3. Count(*) vs Count(Id) w serwerze sql 2005

  4. Czy MS SQL Server między obejmuje granice zakresu?

  5. Po zakleszczeniu jednej transakcji w różnych wersjach programu SQL Server