SQLCookbook中文版:第6章 使用字符串,第7章 使用数字

第6章 使用字符串

SQL的目标不是完成复杂的字符串操作, 在SQL中对字符串进行操作是非常繁琐和令人厌烦的。

本章第6.1节遍历字符串非常重要, 后来很多其他解决方案都要用到它。 在很多情况下需要通过每次移动一个字符的方法来遍历字符串,但遗憾的是,使用SQL就没有这样简单了,因为在SQL中没有循环功能(Oracle的MODEL子句除外), 这就需要模拟一个循环来遍历字符串。

(第6章略)

第7章 使用数字

7.1 计算平均值:avg

不带where子句,会计算所有非 null 值的平均值,如果使用了 coalesec函数转换null,会改变avg的计算结果.

select avg(sal) from emp

计算每个部门的平均工资, 需要使用 group by 按部门分组.**group by 会自动让集合函数(avg等)为每个组返回一个记过.

select deptno , avg(sal) from emp group by deptno

结果:

deptno avg(sal)
10 2916.666667
20 2175.000000
30 1566.666667

7.2 计算某列的最大值最小值:max,min

select max(sal),min(sal) from emp

结果:

max(sal) min(sal)
5000.00 800.00

7.3 对某列的值求和:sum

select sum(sal) from emp

结果:

sum(sal)
29025.00

按分组求和:

select deptno,sum(sal) from emp group by deptno

结果:

deptno sum(sal)
10 8750.00
20 10875.00
30 9400.00

7.4 求返回的行数:count

如果count函数的参数使用 *或常量,就会包含null的计数,如果用列名作为参数不会包含null

求表的行数

select count(*) from emp

结果:

count(*)
14

分组:

select deptno, count(*) from emp group by deptno

结果:

deptno count(*)
10 3
20 5
30 6

使用列名作为count函数的参数:

select deptno, count(comm),count(*),count('1') from emp group by deptno

结果:

deptno count(comm) count(*) count('1')
10 0 3 3
20 0 5 5
30 4 6 6

7.5 求某列非空值的个数:count

select count(comm) from emp;

输出:


count(comm)
4

7.6 生成累计和

关键是 where d.empno <=e.empno

MySQL,PG

select e.ename,e.sal,(select sum(d.sal) from emp d where d.empno <=e.empno) as running_total 
from emp e 
order by running_total

结果:

ename sal running_total
SMITH 800.00 800.00
ALLEN 1600.00 2400.00
WARD 1250.00 3650.00
JONES 2975.00 6625.00
MARTIN 1250.00 7875.00
BLAKE 2850.00 10725.00
CLARK 2450.00 13175.00
SCOTT 3000.00 16175.00
KING 5000.00 21175.00
TURNER 1500.00 22675.00
ADAMS 1100.00 23775.00
JAMES 950.00 24725.00
FORD 3000.00 27725.00
MILLER 1300.00 29025.00

7.7 生成累乘积

(略)

7.8 计算累计差

(略)

7.9 计算模式(频度计数)

(略)

7.10 计算中间值(中位数)

(略)

7.11 求总和的百分比

select ((select sum(sal) from emp where deptno='10')/(sum(sal)))*100 as percent from emp

结果:

percent
30.146425

另一种写法

select deptno,sum(sal)*100/(select sum(sal) from emp)  as percent from emp group by deptno

结果:

deptno percent
10 30.146425
20 37.467700
30 32.385874

7.12 对可空列作聚集: 使用coalesce函数处理null纳入计算

select avg(coalesce(comm,0)) as avg_comm from emp group by deptno

使用 sum,avg函数默认不会计算null

7.13 计算不包含最大值,最小值的均值

select avg(sal) from emp
where sal not in ((select max(sal) from emp),(select min(sal) from emp))

如果最高值或最低值不止一个,都会排除在外.

仅排除一个最高值,一个最低值:

select (sum(sal) -max(sal)-min(sal))/(count(sal)-2) from emp 

7.14 把字母字符串转换为数字

(略)

7.15 改变累计和中的值

(略)

正文完
 
评论(没有评论)