Sqlserver
 sql >> Datenbank >  >> RDS >> Sqlserver

Wie erhalte ich die erste Anmeldung und die letzte Abmeldezeit vom SQL-Server?

;WITH LoginCTE AS
(
    SELECT ID,
           Date,
           MIN(Time) AS MinLogin
    FROM   Table
    WHERE  Type = 'In'
    GROUP BY ID,
             Date
),LogoutCTE AS
(
    SELECT ID,
           Date,
           MAX(Time) AS MaxLogout
    FROM   Table
    WHERE  Type = 'Out'
    GROUP BY ID,
             Date
)
SELECT T.ID,
       T.Name,
       T.Date,
       MinLogin,
       MaxLogout
FROM   Table T
       JOIN LoginCTE I
           ON T.ID = I.ID
              T.Date = I.Date 
       JOIN LogoutCTE O
           ON T.ID = O.ID
              T.Date = O.Date