ORACLE中的KEEP()使用方法

創建測試數據表

create table test(ID  int ,MC  int,SL int);
insert into test
values(1,111,1);
insert into test
values(1,222,1);
insert into test
values(1,333,2);
insert into test
values(1,555,3);
  
insert into test
values(1,666,3);
 
insert into test
values(2,111,1);
insert into test
values(2,222,1);
insert into test
values(2,333,2);
 
insert into test
values(2,555,2);
 
commit;
select * from test;

在這裏插入圖片描述

select id,
      mc,
      sl,
      min(mc) keep(DENSE_RANK first ORDER BY sl) over(partition by id) as min_mc_first,
      max(mc) keep(DENSE_RANK last ORDER BY sl) over(partition by id) as max_mc_last
 from test;

在這裏插入圖片描述

不要混淆keep內(first、last)外(min、max或者其他):

  • min是可以對應last的
  • max是可以對應first的
select id,
       mc,
       sl,
       min(mc) keep(DENSE_RANK first ORDER BY sl) over(partition by id) as min_first,
       max(mc) keep(DENSE_RANK first ORDER BY sl) over(partition by id) as max_first,
       min(mc) keep(DENSE_RANK last ORDER BY sl) over(partition by id) as min_last,
       max(mc) keep(DENSE_RANK last ORDER BY sl) over(partition by id) as max_last
  from test

在這裏插入圖片描述

對於id=1的結果集進行一下解釋
min(mc) keep (DENSE_RANK first ORDER BY sl) over(partition by id):id等於1的數量最小的(DENSE_RANK first )爲
1 111 1
1 222 1
在這個結果中取min(mc) 就是111
max(mc) keep (DENSE_RANK first ORDER BY sl) over(partition by id)
取max(mc) 就是222;
min(mc) keep (DENSE_RANK last ORDER BY sl) over(partition by id):id等於1的數量最大的(DENSE_RANK first )爲
1 555 3
1 666 3
在這個結果中取min(mc) 就是555,取max(mc)就是666
id=2的結果集同理

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章