最大分析功能加窗口排序无法正常工作

时间:2020-03-26 20:07:30

标签: sql oracle

我有一个带有状态和位置的表,以下是数据。我想使用自定义排序按位置划分最高状态。知道需要改变什么吗?现在,它只给出最大值,而与我提到的顺序无关。

自定义顺序为1> 3> 2

status | location
  1    | 11 
  2    | 11 
  2    | 12 
  3    | 12
  3    | 11

位置11的预期结果:1 位置12的预期结果:3

查询:

select max(status) over (partition by location order by decode(status, '1',6,'3',5,'2',4,3) 
                         rows between unbounded preceding and unbounded following) mx from items;

http://sqlfiddle.com/#!4/ed9e7e/13

create table items
( status varchar2(1), location number(9)
);

insert into items values('1',123);

insert into items values('2',123);

insert into items values('3',123);

insert into items values('4',123);

3 个答案:

答案 0 :(得分:2)

我认为您想要<section> <img data-src="lib/dist/images/cake_bottom.png"> </section>

<img>

我不是first_value()的忠实拥护者,但这是表达您想要的内容的简洁方法。我更喜欢select first_value(status) over (partition by location order by decode(status, '1', 6, '3', 5, '2', 4, 3) ) mx from items; 表达式。

答案 1 :(得分:1)

我看到几个问题。您的解码器似乎与您的要求不符。其次,我不认为MAX()是您要使用的函数,因为它在不考虑自定义顺序的情况下返回最大状态。相反,您应该分配按位置划分的行号,并按自定义排序顺序排序。然后选择行号为1的所有行。

create table items
( status varchar2(1), location number(9)
);

insert into items values('1',11);
insert into items values('2',11);
insert into items values('2',12);
insert into items values('3',12);
insert into items values('3',11);

select x.location, x.status
from (
    select ROW_NUMBER() over (partition by location order by decode(status, '1',1,'2',3,'3',2,4)) as rn, 
           status, location from items) x
where x.rn = 1

SQL Fiddle

答案 2 :(得分:1)

我建议使用简单的GROUP BY可能会更容易:

SELECT LOCATION,
       DECODE(MAX(ORDERING), 6, '1', 5, '3', 4, '2', 3) AS STATUS
  FROM (SELECT LOCATION,
               STATUS AS STATUS,
               DECODE(STATUS, '1', 6, '3', 5, '2', 4, 3) AS ORDERING
          FROM ITEMS)
  GROUP BY LOCATION
  ORDER BY LOCATION

db<>fiddle here