SQL时间参数计算

时间:2017-04-19 16:58:12

标签: sql sql-server

我是SQL的新手,他正在尝试创建活动报告,我在表上存储过程和触发器以记录登录和注销日期/时间。

SQL Table Image

我正在考虑如何计算从第一次登录到每天最后一次登出的工作时间?

非常感谢任何指导,谢谢。

1 个答案:

答案 0 :(得分:0)

SELECT A.*,
       DATEDIFF(second,B.firstloginonthatday,B.lastlogoutonthatday) AS time_elapsed
  FROM  YourTable A
INNER JOIN 
    (        SELECT Z.USERID,
                   CONVERT(DATE,Z.DATE_TIME ) AS ONLYDATE,
                   MIN( Z.DATE_TIME ) AS firstloginonthatday,
                   MAX( Z.DATE_TIME ) AS lastlogoutonthatday  
              FROM  
                (
                    SELECT  *,
                            ROW_NUMBER( )
                            OVER 
                            ( PARTITION BY USERID,CONVERT(DATE,DATE_TIME) ORDER BY CASE WHEN action = 'logout' THEN DATE_TIME 
                              ELSE NULL END
                             ) AS lastlogout_rn,            
                            ROW_NUMBER( )
                            OVER 
                            ( PARTITION BY USERID,CONVERT(DATE,DATE_TIME) ORDER BY CASE WHEN action = 'login' THEN DATE_TIME 
                              ELSE NULL END
                             ) AS firstlogin_rn     
                      FROM Yourtable
                 ) Z
           WHERE Z.lastlogout_rn = 1 OR Z.firstlogin_rn = 1
           GROUP BY Z.USERID,CONVERT(DATE,Z.DATE_TIME )
    ) B
   ON A.USERID = B.USERID
  AND CONVERT(DATE,A.DATE_TIME) = B.ONLYDATE;