Oracle SQL分组/排序

时间:2014-04-07 20:47:02

标签: sql oracle group-by sql-order-by

我正在寻找一些帮助来编写Oracle SQL语句来完成以下操作......

假设我有以下数据:

YEAR | PLACE
1984 | somewhere
1983 | work
1985 | somewhere
1982 | home
1984 | work
1983 | home
1984 | somewhere

如何获得将所有PLACE列值保持在一起并按YEAR列排序的结果...所以我要找的结果是:

YEAR | PLACE
1982 | home
1983 | home
1983 | work
1984 | work
1984 | somewhere
1984 | somewhere
1985 | somewhere

感谢。

编辑:

只是为了说明一些问题的答案...让我说我将以下数据添加到原始数据中:

1981 | somewhere

现在结果应该是:

YEAR | PLACE
1981 | somewhere
1984 | somewhere
1984 | somewhere
1985 | somewhere
1982 | home
1983 | home
1983 | work
1984 | work

感谢。

2 个答案:

答案 0 :(得分:4)

您可以使用窗口聚合函数来实现此目的:

SELECT 
    year, 
    place
FROM 
    tablename
ORDER BY
    MIN(year) OVER (PARTITION BY place),
    place,
    year ;

经过测试: SQLfiddle.com

答案 1 :(得分:1)

根据OP的意见修改:

select a.year, a.place
from my_table a join
  (select place, min(year) as min_year from my_table group by place) b on a.place = b.place
order by b.min_year, a.place, a.year