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的结果集同理

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值