第一个和最后一个值ORACLE

时间:2014-02-12 14:31:08

标签: sql oracle

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

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

使用另一个查询的输出

   column1 |time
    ________|_______
      ABC   | 00:00:01
      ABC   | 00:00:02
      ABC   | 00:00:03
      123   | 00:00:04
      123   | 00:00:05
      123   | 00:00:06
      123   | 00:00:07

我可以在这里使用“第一个”或“最后一个”的命令吗[就像在XPath中一样]?试过GROUP BY,但它不能正常工作:(

谢谢!

1 个答案:

答案 0 :(得分:3)

您可以将其放在两列中,这将是更自然的方法:

select column1, min(time) as firsttime, max(time) as lasttime
from t
group by column1;

你真的想要四行输出,两行上有END,但不能识别结尾的内容吗?

编辑:

获得所需的输出:

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;

请注意order by子句。结果不保证按任何特定顺序排列,排序对于理解这些结果很重要。