SQL:最旧项目的年龄

时间:2015-05-05 07:21:37

标签: sql oracle select max

我有以下Oracle数据库。某个ID可以具有已接受状态,但可以继续处于失败状态,并以可接受状态返回。这可能发生在X时间,因此可以称为循环

ID       STATUS         TIME INSERT
------------------------------
1        Accepted       01:00:00
1        Failed         02:00:00
1        Accepted       02:30:00
2        Accepted       02:33:00

我想计算具有已接受状态的最旧项目的年龄。 这意味着SYSDATE - TIME INSERT

的结果
  

作为此数据的结果,我期望3d记录时间值,02:30:00

我需要检查每个ID的最年轻时间,以及ID的所有最年久的最老生命周期。 这看起来很复杂。

工作流程步骤为:

  1. 处于接受状态的特定ID的最小时间值
  2. 接受状态下每个ID的第1步
  3. 我在步骤2中计算的所有最小值的最大值。
  4. 此刻我有以下代码

    select min(TO_CHAR(TO_DATE('20000101','yyyymmdd')+(SYSDATE - dm1.time_insert),'hh24:mi:ss'))
    from db dm1 
    where dm1.status='accepted'
    group by dm1.id;
    

    这给了我一系列所有记录的最小值。但是现在我需要所有这些最小值的最大值,我该怎么做? 谁能解决这个案子?

2 个答案:

答案 0 :(得分:3)

希望这会对你有所帮助:

-- this will give you the minimum date of all id's
select * from tab1 where TIME_INSERT  in (select min(TIME_INSERT) from tab1 )and STATUS ='Accepted'


-- this will give you the minimum date of a specefique id 
select * from tab1 where TIME_INSERT  in (select min(TIME_INSERT) from tab1 )
and STATUS ='Accepted' and ID =1

检查这个

select id, TIME_INSERT from
 (select TIME_INSERT, ID , min(TIME_INSERT) over (partition by ID) maxid from tab1) 
where TIME_INSERT = maxid and TIME_INSERT in(select max(TIME_INSERT) from tab1) group by ID,TIME_INSERT

答案 1 :(得分:2)

你可以找到max(time_insert)和id by group。看一下示例查询

    with src as (
select 1 as id, 'Accepted' as status, to_date('2015-05-05 01:00:00','yyyy-mm-dd hh24:mi:ss') as time_insert from dual
union all
select 1 as id, 'Failed' as status, to_date('2015-05-05 02:00:00','yyyy-mm-dd hh24:mi:ss') as time_insert from dual
union all 
select 1 as id, 'Accepted' as status, to_date('2015-05-05 02:30:00','yyyy-mm-dd hh24:mi:ss') as time_insert from dual
union all
select 2 as id, 'Accepted' as status, to_date('2015-05-05 02:33:00','yyyy-mm-dd hh24:mi:ss') as time_insert from dual)

select id, max(time_insert) as time_insert, max(sysdate - time_insert) as lifetime_max, min(sysdate - time_insert) as liftime_min from src 
where status ='Accepted'
group by id
  

编辑:这是你想要实现的目标:

with src as (
select 1 as id, 'Accepted' as status, to_date('2015-05-05 01:00:00','yyyy-mm-dd hh24:mi:ss') as time_insert from dual
union all
select 1 as id, 'Failed' as status, to_date('2015-05-05 02:00:00','yyyy-mm-dd hh24:mi:ss') as time_insert from dual
union all 
select 1 as id, 'Accepted' as status, to_date('2015-05-05 02:30:00','yyyy-mm-dd hh24:mi:ss') as time_insert from dual
union all
select 2 as id, 'Accepted' as status, to_date('2015-05-05 02:33:00','yyyy-mm-dd hh24:mi:ss') as time_insert from dual)
, src2 as (
select max(time_insert) as time_insert, max(sysdate - time_insert) as lifetime_max, min(sysdate - time_insert) as lifetime_min from src 
where status ='Accepted')
select max(lifetime_min) from src2