返回最值所在行数据

创建测试用表:

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;

posted on 2015-10-20 19:25  奈何作贼  阅读(241)  评论(0编辑  收藏  举报

导航