3,490
社区成员
发帖
与我相关
我的任务
分享
select id,
max(decode(rn,1,time,null)) time_in,
max(decode(rn,1,type,null)) type_in,
max(decode(rn1,1,time,null)) time_out,
max(decode(rn1,1,type,null)) type_out
from (select id, time,type,
row_number()over(partition by id,trunc(time) order by time) rn,
row_number()over(partition by id,trunc(time) order by time desc) rn1
from tmp
)
group by id;
--1.创建测试表
create table tmp as
select '1001' id, to_date('2017-01-01 12:12:12 ','yyyy-mm-dd hh24:mi:ss') time, 1 type from dual union all
select '1001' id, to_date('2017-01-01 19:19:19 ','yyyy-mm-dd hh24:mi:ss') time, 2 type from dual union all
select '1002' id, to_date('2017-01-01 10:10:10 ','yyyy-mm-dd hh24:mi:ss') time, 1 type from dual union all
select '1002' id, to_date('2017-01-01 20:20:20 ','yyyy-mm-dd hh24:mi:ss') time, 2 type from dual union all
select '1003' id, to_date('2017-01-01 13:13:13 ','yyyy-mm-dd hh24:mi:ss') time, 1 type from dual union all
select '1003' id, to_date('2017-01-01 16:16:16 ','yyyy-mm-dd hh24:mi:ss') time, 2 type from dual
--2.SQL实现
select id,
max(decode(rn,1,time,null)) time_in,
max(decode(rn,1,type,null)) type_in,
max(decode(rn1,1,time,null)) type_out,
max(decode(rn1,1,type,null)) type_out
from (select id, time,type,
row_number()over(partition by id order by time) rn,
row_number()over(partition by id order by time desc) rn1
from tmp
)
group by id;
--1.创建测试表
create table tmp as
select '1001' id, to_date('2017-01-01 12:12:12 ','yyyy-mm-dd hh24:mi:ss') time, 1 type from dual union all
select '1001' id, to_date('2017-01-01 16:16:16 ','yyyy-mm-dd hh24:mi:ss') time, 1 type from dual union all
select '1001' id, to_date('2017-01-01 11:11:11 ','yyyy-mm-dd hh24:mi:ss') time, 2 type from dual union all
select '1001' id, to_date('2017-01-01 19:19:19 ','yyyy-mm-dd hh24:mi:ss') time, 2 type from dual union all
select '1001' id, to_date('2017-01-01 20:20:20 ','yyyy-mm-dd hh24:mi:ss') time, 2 type from dual union all
select '1002' id, to_date('2017-01-01 10:10:10 ','yyyy-mm-dd hh24:mi:ss') time, 1 type from dual union all
select '1002' id, to_date('2017-01-01 20:20:20 ','yyyy-mm-dd hh24:mi:ss') time, 2 type from dual union all
select '1003' id, to_date('2017-01-01 13:13:13 ','yyyy-mm-dd hh24:mi:ss') time, 1 type from dual union all
select '1003' id, to_date('2017-01-01 16:16:16 ','yyyy-mm-dd hh24:mi:ss') time, 2 type from dual
--2.SQL实现: 同一用户id下,取type=1 create_time最小的记录,type =2 create_time最大的记录
select id,
max(decode(rn,1,time,null)) time_in,
max(decode(rn,1,type,null)) type_in,
max(decode(rn1,1,time,null)) time_out,
max(decode(rn1,1,type,null)) type_out
from (select id, time,type,
case when type = 1 then row_number()over(partition by id,type,trunc(time) order by time) else null end rn,
case when type = 2 then row_number()over(partition by id,type,trunc(time) order by time desc) else null end rn1
from tmp
where type in (1,2)
)
group by id;