如何从sql中的多个列获取持续时间?

时间:2017-12-11 13:32:08

标签: sql sql-server

Demo Query:

这个我的表与demo中的相同,我使用相同的查询。我需要得到所有特定员工的总持续时间......我试了很多..

    select
       id, cast(time_stamp as date) [date]
     , format(max(case when in_rank = 1 then time_stamp end),'HH:mm') check_in_1
     , format(max(case when in_rank = 1 then next_timestamp end),'HH:mm') check_out_1
     , format(max(case when in_rank = 1 then 
           dateadd(ss,datediff(ss,time_stamp,next_timestamp),0)
           end),'HH:mm') total_hrs_1
     , format(max(case when in_rank = 2 then time_stamp end),'HH:mm') check_in_2
     , format(max(case when in_rank = 2 then next_timestamp end),'HH:mm') check_out_2
     , format(max(case when in_rank = 2 then
           dateadd(ss,datediff(ss,time_stamp,next_timestamp),0)
           end),'HH:mm') total_hrs_2
from (
      select
            id, time_stamp, AccessType, next_timestamp, next_accesstype
          , dense_rank() over(partition by id, cast(time_stamp as date) order by time_stamp) in_rank
      from table1 t1
      outer apply (
          select top(1) t2.time_stamp, t2.AccessType
          from table1 t2
          where t1.id = t2.id and t1.AccessType <> t2.AccessType
          and cast(t1.time_stamp as date) = cast(t2.time_stamp as date)
          and t1.time_stamp < t2.time_stamp
          order by t2.time_stamp
          ) oa (next_timestamp, next_accesstype)
      where AccessType = 0
     ) d
group by id, cast(time_stamp as date)

预期产出:

id  date    check_in_1  check_out_1 total_hrs_1 check_in_2  check_out_2 total_hrs_2  Grand Total
1001    2017-09-05      09:35       12:00       02:25     09:36     12:00       02:24     4:49
1002    2017-09-05      11:00       12:25       01:25     14:00     18:00       04:00     5:25

0 个答案:

没有答案