用于隔离两个不同列中的列的最大值和最小值的SQL查询表示Val1和Val2

时间:2016-09-28 04:06:44

标签: sql oracle oracle11g

我有下表:

ID DateVal Val
1 1/1/2010 a
1 2/2/2010 b
1 3/3/2010 c
2 4/4/2010 d
2 5/5/2010 e
2 6/6/2010 f
3 7/7/2010 g
3 8/8/2010 h
3 9/9/2010 i

我需要以下内容:

ID Val1 Val2
1 a c
2 d f
3 g i

即。 Val在最小日期在'Val1'栏中,Val和最大日期在'Val2'栏中 有什么查询可以实现这个输出,哪一个最容易?

2 个答案:

答案 0 :(得分:3)

DDL

with T as (
select 1 as id, to_date('01.01.2010','DD.MM.YYYY') dt, 'a' val
from dual union all
select 1 as id, to_date('02.02.2010','DD.MM.YYYY') dt, 'b' val
from dual union all
select 1 as id, to_date('03.03.2010','DD.MM.YYYY') dt, 'c' val
from dual union all
select 2 as id, to_date('04.04.2010','DD.MM.YYYY') dt, 'd' val
from dual union all
select 2 as id, to_date('05.05.2010','DD.MM.YYYY') dt, 'e' val
from dual union all
select 2 as id, to_date('06.06.2010','DD.MM.YYYY') dt, 'f' val
from dual union all
select 3 as id, to_date('07.07.2010','DD.MM.YYYY') dt, 'g' val
from dual union all
select 3 as id, to_date('08.08.2010','DD.MM.YYYY') dt, 'h' val
from dual union all
select 3 as id, to_date('09.09.2010','DD.MM.YYYY') dt, 'i' val
from dual)

代码

  select 
  id,
  max(val) keep (dense_rank first order by dt) as maxs,
  max(val) keep (dense_rank first order by dt desc) as mins from t 
group by id

答案 1 :(得分:-1)

with t1 as 
 (select ID, min(dtval) dtval, min(val) val from date_val group by ID), 

t2 as
 (select ID, max(dtval) dtval, max(val) val from date_val group by ID)

select t1.id, t1.val val1, t2.val val2 from t1 join t2 on t1.id = t2.id;