1. 程式人生 > >SQL語句之計算次數出現最多的值

SQL語句之計算次數出現最多的值

需求,計算20號部門員工工資出現的次數
使用count() 函式:

SQL> select sal,count(*) time from emp where deptno=20 group by sal;

       SAL   TIME
---------- ----------
      2975      1
      1100      1
      3000      2
       800      1

SQL> 

計算20號部門工資出現的次數,並排出序號
使用dense_rank分析函式

SQL> select sal,dense_rank() over(order
by time desc) as seq 2 from 3 (select sal,count(*) time from emp where deptno=20 group by sal) emp; SAL SEQ ---------- ---------- 3000 1 800 2 2975 2 1100 2 SQL>

根據序號過濾得到序號為2的結果

SQL> select sal
  2  from
  3  (select sal,dense_rank() over(order
by time desc) as seq 4 from 5 (select sal,count(*) time from emp where deptno=20 group by sal) emp) emp 6 where seq=2; SAL ---------- 2975 800 1100 SQL>

利用partition by 子句分別查詢各個部門哪個工資等級的員工多

SQL> select deptno,sal
  2  from
  3  (select deptno,sal,dense_rank() over(partition by
deptno order by time desc) as seq 4 from 5 (select deptno,sal,count(*) time from emp group by deptno,sal) emp ) emp 6 where seq=1; DEPTNO SAL ---------- ---------- 10 5000 10 1300 10 2450 20 3000 30 1250 SQL>

以上就是計算次數出現最多的次數的方法。