我想基于相同的位置和相同的日期添加到第一个值checkin
和最后一个值checkout
。
我运行此查询:
select USERID , CHECKTIME , SENSORID
from CHECKINOUT
where USERID = 15
我的意思是:
USERID CHECKTIME SENSORID
------------------------------------
15 2014-10-20 01:22:01.000 100
15 2014-10-20 12:38:22.000 100
15 2014-10-20 22:00:54.000 100
15 2014-10-21 01:24:30.000 100
15 2014-10-21 07:31:39.000 100
15 2014-10-21 22:11:47.000 100
15 2014-10-22 00:10:34.000 100
15 2014-10-22 05:51:47.000 100
是:
USERID CHECKTIME SENSORID
---------------------------------------------
15 2014-10-20 01:22:01.000-checkin 100
15 2014-10-20 12:38:22.000-checkout 100
15 2014-10-20 22:00:54.000-checkin 100
15 2014-10-21 01:24:30.000-checkin 100
15 2014-10-21 07:31:39.000-checkout 100
15 2014-10-21 22:11:47.000-checkin 100
15 2014-10-22 00:10:34.000-checkin 100
15 2014-10-22 05:51:47.000-checkout 100
但基于sensorid
的日期相同且相同。
答案 0 :(得分:0)
尝试这样
select USERID,CHECKTIME + case when code % 2 =0 then '- Check out'
else ' -Check IN' end,SENSORID from (
select *,ROW_NUMBER() over(PARTITION BY USERID,CHECKTIME
order by USERID ,CHECKTIME) code
from table1) as t1
答案 1 :(得分:0)
试试这个,这可以帮到你:
select userid,convert(varchar(30),checktime,121) +
case when
((row_number() over (partition by userid,sensorid,convert(varchar(30),checktime,101)
order by checktime))%2 = 0)
then '-checkout'
else '-checkin' end
as checktime,sensorid
from temt
where userid = 15
here是demo sql fiddle
如果您想添加一个包含值的新列,则可以使用以下解决方案:
alter table temt
add checkinorout varchar(50)
;with cte_update (userid,checkinorout,ctime,sensorid) as
(
select userid,checkinorout,convert(varchar(30),checktime,121) +
case when
((row_number() over (partition by userid,sensorid,convert(varchar(30),checktime,101)
order by checktime))%2 = 0)
then '-checkout'
else '-checkin' end
as ctime,sensorid
from temt
)
update cte_update set checkinorout = ctime
select * from temt
here是demo sql fiddle。