with cte as
(SELECT * ,row_number()over(order by clocktime)as n FROM #CLOCK ),
cte1 as
(select * from cte as a
where clocktype ='in' and not exists
(select 2 from cte as b where a.n-b.n=1 and b.clocktype=a.clocktype)
union all
select * from cte as a
where clocktype ='out' and not exists
(select 2 from cte as b where b.n-a.n=1 and b.clocktype=a.clocktype))
select sysuser,[in] as clockin ,[out] as clockout, clockdt from
(select sysuser,clocktype,clocktime,clockdt ,
row_number()over(partition by clocktype order by clocktime) as n from cte1) as t
pivot ( max(clocktime) for clocktype in([in],[out])) as p
--我的理解就是第一个in和最后一个out
;WITH cte AS (
SELECT rn=ROW_NUMBER() OVER(ORDER BY clocktime),* FROM #CLOCK
)
SELECT u.*,v.CLOCKTIME FROM (
SELECT n=ROW_NUMBER() OVER(ORDER BY rn),* FROM cte a WHERE a.CLOCKTYPE='IN' AND NOT EXISTS(SELECT 1 FROM cte WHERE CLOCKTYPE='IN' AND rn=a.rn-1)
) U JOIN (
SELECT n=ROW_NUMBER() OVER(ORDER BY rn),* FROM cte a WHERE a.CLOCKTYPE='OUT' AND NOT EXISTS(SELECT 1 FROM cte WHERE CLOCKTYPE='OUT' AND rn=a.rn+1)
) V ON u.n=v.n