![](/img/trans.png)
[英]Aggregate window functions with an ORDER BY clause require a frame clause SQL
[英]Oracle SQL: Custom ORDER BY clause with a window aggregate function
我正在研究一个Oracle SQL语句,该语句可以执行我需要的一些高级排序。 到目前为止,这是我的声明:
SELECT TIME, PLACE
FROM TABLENAME
ORDER BY MIN(year) OVER (PARTITION BY PLACE), PLACE, TIME;
在获得其他问题( Oracle SQL分组/订购 )的帮助后,我将它们放在一起。 现在我需要把季节混合在一起,但是,现有数据库中没有对它们进行数字编号。
所以说我有以下数据
TIME | PLACE
198410 | somewhere
198320 | work
198431 | somewhere
198232 | home
198322 | work
198211 | home
198422 | somewhere
TIME列的前四位数字是年份,下一位数字是季节(其中2 =夏季,3 =秋季,1 =冬季),最后一位应忽略(出于比较原因)。
上面的查询将产生以下结果(将地点分组并根据时间对它们进行排序(数字方式)):
TIME | PLACE
198410 | somewhere
198422 | somewhere
198431 | somewhere
198320 | work
198322 | work
198211 | home
198232 | home
但是,我需要一个查询,该查询将考虑奇怪的编码季节(夏季= 2,秋季= 3,冬季= 1),并产生以下按时间排序的结果:
TIME | PLACE
198422 | somewhere
198431 | somewhere
198410 | somewhere
198320 | work
198322 | work
198232 | home
198211 | home
我没有制定这个标准,但是不幸的是我必须使用它。 非常感谢您提供帮助以解决此问题。
您可以使用解码或case语句来“修正”即时的季节排序。 (您没有“春天”吗?)
select time, place
from tablename
order by max(substr(time, 1, 4) || case substr(time, 5, 1)
when '2' then 1 when '3' then 2 when '1' then 3 end)
over (partition by place) desc,
place,
substr(time, 1, 4) desc,
case substr(time, 5, 1) when '2' then 1 when '3' then 2 when '1' then 3 end;
您似乎按降序排序年份,而代码示例没有这样做,但这与您想要的输出匹配:
TIME PLACE
------ ---------
198422 somewhere
198431 somewhere
198410 somewhere
198320 work
198322 work
198232 home
198211 home
SQL小提琴 。
在重复进行年份提取和调整后的季节计算时,您可能希望在子查询中处理一次:
select time, place
from (
select time, place, substr(time, 1, 4) as year,
case substr(time, 5, 1) when '2' then 1 when '3' then 2 when '1' then 3 end
as season
from tablename
)
order by max(year || season) over (partition by place) desc,
place, year desc, season;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.