一張t2表:
select * from t2
sql
select AVG(sal) from t2
獲得的結果是:
3d
原本咱們獲得的結果應該是10的。可是獲得的結果確實15.code
這是由於忽略了null值。blog
解決方案:
當爲空的時候轉換爲0數學
select AVG(coalesce(sal,0)) from t2
max與min會忽略null,可是若是全是null的狀況,會返回null值。class
select DEPTNO,max(COMM) from EMP where DEPTNO in (10,30) group by DEPTNO
例如:
select
解決方法:
如上文方法
select DEPTNO,max(coalesce(COMM,0)) from EMP where DEPTNO in (10,30) group by DEPTNO
sum 計算的時候會忽略null值。
如上:
解決:im
select DEPTNO,sum(coalesce(COMM,0)) from EMP where DEPTNO in (10,30) group by DEPTNO
一般咱們計算行數,一般是使用count。d3
一樣是會忽略null值:
select COUNT(*),count(COMM) from EMP
要實現下面這種效果:
好比2600,是紅框部分的和。
假設前兩列的效果是:
select e.EMPNO, e.SAL from EMP e order by 1
要求寫出第三列的效果。
答案:
select e.EMPNO, e.SAL,(select SUM(d.SAL) from EMP d where d.EMPNO<=e.EMPNO) as total from EMP e order by 3
如何實現累計乘法?
有一個數學概念:
select e.EMPNO, e.SAL,(select exp(sum(log(d.SAL))) from EMP d where d.EMPNO<=e.EMPNO and d.DEPTNO=e.DEPTNO ) as total from EMP e where DEPTNO=10 order by 3
分狀況討論,當是第一個直接輸出第一個。後面的就是所有是負值相加而後加兩個EMPNO最小值。
select e.EMPNO, e.SAL,(select case when e.EMPNO=MIN(d.EMPNO) then sum(d.SAL) else sum(-d.SAL)+(select f.SAL from emp f where f.EMPNO=MIN(d.EMPNO))*2 end from EMP d where d.EMPNO<=e.EMPNO and d.DEPTNO=e.DEPTNO ) as total from EMP e where DEPTNO=10 order by EMPNO