Min Max with ID - Oracle

时间:2014-02-12 15:40:38

标签: sql oracle

尝试在Oracle 8i中获取此输出:

column1 |time
________|_______
  ABC   | 00:00:01
  END   | 00:00:03
  123   | 00:00:04
  END   | 00:00:07
  ABC   | 00:00:08
  END   | 00:00:10

使用另一个查询的输出

   column1  |time       |ID
    ________|___________|
      ABC   | 00:00:01  |  1
      ABC   | 00:00:02  |  1
      ABC   | 00:00:03  |  1 
      123   | 00:00:04  |  1
      123   | 00:00:05  |  1
      123   | 00:00:06  |  1
      123   | 00:00:07  |  1
      ABC   | 00:00:08  |  2
      ABC   | 00:00:09  |  2
      ABC   | 00:00:10  |  2

此查询获取最小值和最大值而不考虑ID。

select (case when n.n = 1 then column1 else 'END' end) as column1,
       (case when n.n = 1 then firsttime else lasttime end) as "time"
from (select column1, min(time) as firsttime, max(time) as lasttime
      from t
      group by column1
     ) t cross join
     (select 1 as n from dual union all select 2 from dual) n
order by column1, n.n;

如何做同样的事情但是不考虑第1列中出现的第一个和最后一个值,还要考虑ID吗?

1 个答案:

答案 0 :(得分:0)

您需要在idgroup by中的逻辑中加入order by

select (case when n.n = 1 then column1 else 'END' end) as column1,
       (case when n.n = 1 then firsttime else lasttime end) as "time"
from (select column1, id, min(time) as firsttime, max(time) as lasttime
      from t
      group by column1, id
     ) t cross join
     (select 1 as n from dual union all select 2 from dual) n
order by id, column1, n.n;