这是我的表格数据
id EVENTID DT
1 1 2018-06-21 16:00:00.000
1 4 2018-06-21 14:00:00.000
1 3 2018-06-21 13:00:00.000
1 4 2018-06-21 11:00:00.000
1 3 2018-06-21 10:00:00.000
1 0 2018-06-21 08:17:12.000
Eventid: 0 in 1出 3作为突破 4作为闯入
我使用过以下查询,但无法在同一行中获取所有中断时间
select
t.emp_reader_id as empId,B.emp_name, cast(max(DT) as date) as Belongs_to,B.areaname as POINTID, max(iif(EVENTID = 0, DT, null)) as EntryTime, max(iif(EVENTID = 1, DT, null)) as ExitTime,
max(iif(EVENTID = 3, DT, null)) as Breakin, max(iif(EVENTID = 4, DT, null)) as Breakout,
format(dateadd(ss,Datediff(second,max(iif(EVENTID = 0, DT, null)),max(iif(EVENTID = 1, DT, null))),0),'HH:mm') as Worked
,CONVERT( CHAR(11), @Date_From, 103 ) as StartDate
,CONVERT( CHAR(11), @Date_To, 103 ) as ToDate
from (
select
*, grp =sum(iif(EVENTID = 1,0, 0) ) over (partition by emp_reader_id order by DT) ,
grp1 = sum(iif(EVENTID = 3,4, 0) )over (partition by emp_reader_id order by DT)
from
Trnevents
) t inner join employee B on t.emp_reader_id=B.emp_reader_id
group by t.emp_reader_id,t.grp,B.emp_name,t.Belongs_to,B.areaname
预期输出:
empId emp_name Belongs_to POINTID EntryTime ExitTime Breakout1 Breakout1 Breakout2 Breakout2 Worked StartDate ToDate
1 *** 2018-06-21 *** 2018-06-21 08:17:12 2018-06-21 16:00:00 2018-06-21 11:00:00 2018-06-21 13:00:00 2018-06-21 13:00:00 2018-06-21 14:00:00 05:42 2018-06-21 2018-06-21
预先感谢
答案 0 :(得分:0)
正如您所建议的那样,突破次数有限,只要按照顺序进行就可以了,直到最后。
我以某种方式看待这个问题,如果多个id的中断次数不同,那么它可能会导致您进入动态sql。
SELECT id AS empid, convert(varchar , stbstr(tt, 1, 10) , 2) AS Belongs_to,
convert(varchar ,stbstr(TT, instr(TT, '$1', 1), instr(TT, '$1', 1)+23) , 2) AS EntryTime,...
FROM (
SELECT id, string_agg(dt + '$' + cast(EventID AS VARCHAR) + DT , ',') AS TT
FROM time_table
GROUP BY id
)