用于创建范围的SQL

时间:2015-09-15 15:56:27

标签: sql database oracle11g

我的下表有2列

Dept   |   Term  

A      |    2010
A      |    2011
B      |    2012
C      |    2013

我想创建最大值和最小值列,以使输出看起来如下表所示。可以使用min()函数和term列分组获得最小值。最大值应该是下一组的最小值。

Dept   |   min_Term  | max_term

A      |    2010     |  2012
B      |    2012     |  2013
C      |    2013     |  Null

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:3)

您可以使用lead函数从下一行获取最小值项。

with t1 as (
select dept, min(term) mnterm
from table
group by dept)
, t2 as (select dept, mnterm as min_term, lead(mnterm) over(order by dept) as max_term
         from t1)
select * from t2;

答案 1 :(得分:0)

您可以将聚合和分析函数组合在一起,如下所示:

select dept
     , min(term) min_term
     , lead(min(term)) over (order by dept) max_term
  from table
 group by dept;