Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Come ottenere il primo accesso e l'ultima volta di logout dal server sql?

;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