[Oracle]高效的SQL語句之分析函數(一)–sum()

來源:互聯網
上載者:User

 

實際應用中我們可以通過sum()統計出組中的總計或者是累加值,具體樣本如下:

1.建立示範表

create table emp
as
select * from scott.emp;

alter table emp
add constraint emp_pk
primary key(empno);

create table dept
as
select * from scott.dept;

alter table dept
add constraint dept_pk
primary key(deptno);

2. sum()語句如下:

select deptno,
       ename,
       sal,
  --按照部門薪水累加(order by改變了分析函數的作用,只工作在當前行和前一行,而不是所有行)
       sum(sal) over (partition by deptno order by sal) CumDeptTot,  
       sum(sal) over (partition by deptno) SalByDept,  --統計一個部門的薪水
       sum(sal) over (order by deptno,sal) CumTot,  --所有僱員的薪水一行一行的累加
       sum(sal) over () TotSal  --統計總薪水
  from emp
 order by deptno, sal

3. 結果如下:

10    MILLER    1300.00    1300    8750    1300    29025
10    CLARK    2450.00    3750    8750    3750    29025
10    KING    5000.00    8750    8750    8750    29025
20    SMITH    800.00    800    10875    9550    29025
20    ADAMS    1100.00    1900    10875    10650    29025
20    JONES    2975.00    4875    10875    13625    29025
20    SCOTT    3000.00    10875    10875    19625    29025
20    FORD    3000.00    10875    10875    19625    29025
30    JAMES    950.00    950    9400    20575    29025
30    WARD    1250.00    3450    9400    23075    29025
30    MARTIN    1250.00    3450    9400    23075    29025
30    TURNER    1500.00    4950    9400    24575    29025
30    ALLEN    1600.00    6550    9400    26175    29025
30    BLAKE    2850.00    9400    9400    29025    29025

 

 

 

 

 

 

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.