码迷,mamicode.com
首页 > 其他好文 > 详细

返回最值所在行数据

时间:2015-10-20 21:18:06      阅读:301      评论:0      收藏:0      [点我收藏+]

标签:

创建测试用表:

CREATE OR REPLACE VIEW v AS
SELECT ‘10‘ AS depno, ‘101‘ AS empno, ‘A‘ AS ename, ‘2000‘ AS sal FROM DUAL
UNION ALL
SELECT ‘10‘ AS depno, ‘102‘ AS empno, ‘B‘ AS ename, ‘1000‘ AS sal FROM DUAL
UNION ALL
SELECT ‘10‘ AS depno, ‘103‘ AS empno, ‘C‘ AS ename, ‘2500‘ AS sal FROM DUAL
UNION ALL
SELECT ‘20‘ AS depno, ‘104‘ AS empno, ‘D‘ AS ename, ‘2000‘ AS sal FROM DUAL
UNION ALL
SELECT ‘20‘ AS depno, ‘105‘ AS empno, ‘E‘ AS ename, ‘4000‘ AS sal FROM DUAL
UNION ALL
SELECT ‘20‘ AS depno, ‘106‘ AS empno, ‘F‘ AS ename, ‘4000‘ AS sal FROM DUAL;

SELECT * FROM v;

SQL代码如下:

SELECT depno,
       empno,
       MAX(ename) KEEP(DENSE_RANK FIRST ORDER BY sal) OVER(PARTITION BY depno) AS min,
       MAX(ename) KEEP(DENSE_RANK LAST ORDER BY sal) OVER(PARTITION BY depno) AS max,
       ename,
       sal
  FROM v
 ORDER BY depno, sal DESC;

执行结果如下:

技术分享

另外,first、last语句也可以放在group里,与其他聚合函数一起使用,这时要去掉后面的over(partition by xxx):

SELECT depno,
       MIN(sal) AS min_sal,
       MAX(ename) KEEP(DENSE_RANK FIRST ORDER BY sal) AS min_name,
       MAX(sal) AS max_sal,
       MAX(ename) KEEP(DENSE_RANK LAST ORDER BY sal) AS max_nam
  FROM v
 GROUP BY depno;

技术分享

返回最值所在行数据

标签:

原文地址:http://www.cnblogs.com/minisculestep/p/4895852.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!