Oracle SQL Grouping/Ordering

喜你入骨 提交于 2019-12-13 21:09:58

问题


I'm looking for some help in writing an Oracle SQL statement to accomplish the following ...

Let's say I have the following data:

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

How can I get a result that keeps all the PLACE column values together and orders it by the YEAR column ... so the result I'm looking for is:

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

Thanks.

EDIT:

Just to illustrate answers to some of the questions asked ... let's say I add the following data to my original data:

1981 | somewhere

Now the result should be:

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

Thanks.


回答1:


You can achieve this with a window aggregate function:

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

Tested at: SQLfiddle.com




回答2:


REVISED base on the OPs comments:

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


来源:https://stackoverflow.com/questions/22922772/oracle-sql-grouping-ordering

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!