python count函数用法 comm_学习python第23天

今天是在尚学堂学习python第23天今天学习了多行函数,分组统计,having子句,多表查询。

多行函数

1.多行函数:操作一组数据(多行记录) 返回一个结果 也叫分组函数

2.多行函数大多使用于统计

例如:统计各部门中雇员的人数

统计各部门中最高最低薪资是多少

3.多行函数主要有:

(1)count()统计表中记录的数目

count()的使用

a.统计表中记录的总数目count(*)

例如查询雇员表中有多少条记录

select count(*) from emp;

b.count(exp)统计exp值非空的记录数目

例如:查询雇员表中有多少位雇员有津贴

select count(comm) from emp;

c.count(distinct(exp)) 返回表达式exp的值不重复且非空的总记录数目

例如:统计雇员表中有多少位雇员是领导

select count(distinct(mgr)) from emp;--统计的是除董事长外的领导人数

统计雇员表中所有领导

ifnull(值1,值2) 如果值1不为null返回值1 ,否则返回值2

select count(distinct(ifnull(mgr,1))) from emp;

(2)sum()

a.sum(exp):返回表达式值得总和

例如 select sum(sal) from emp;

b.sum(distinct(exp))返回不重复的表达式exp的总和

例如select sum(sal),sum(distinct(sal)) from emp;

(3)avg()

a.avg(exp):返回表达式值得平均值

例如: select avg(sal) from emp;

b.avg(distinct(exp)):返回不重复的表达式exp的平均值

例如 select avg(distinct(sal)) from emp;

(4)max() min()

max(exp):返回表达式值得最大值

min(exp):返回表达式值得最小值

例如select min(sal),max(sal) from emp;

分组统计

1.语法:

select 查询内容

from 表名

[where 条件]

[group by 分组字段名1,分组字段名2...]

[order by 字段名 asc|desc]

[limit]

2.使用举例

a.求每个部门的人数

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

b.求每个部门的平均工资

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

c.求每个部门中最高工资和人数

select deptno,max(sal),count(*) from emp group by deptno;

d.求每个岗位的人数

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

e.显示每个部门不同岗位的人数

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

3.注意

a.查询字段,如果没有在多行函数中包含,则必须是分组字段

select ename,job,sum(sal) from emp group by job;

b.如果没有group by ,查询字段不能与多行函数一起查询

select sal,empno from emp; 合法

select sum(sal),empno from emp; 不合法

c.不允许在where条件中使用多行函数

having子句

1.语法:

select 查询内容

from 表名

[where 条件]

[group by 分组字段]

[having 条件]

[order by]

select from --where过滤---group by--having过滤

2.使用举例

a.每个部门不同岗位的人数,且人数大于2

select count(*) from emp where count(*)>2 group by deptno,job

select count(*) from emp group by deptno,job having count(*)>2

b.在emp表中列出工资最小值小于2000的职位

--查询每个职位的最低薪资

select job,min(sal) from emp group by job;

select job,min(sal) from emp group by job having min(sal)<2000;

c.列出平均工资大于1200的部门和职位搭配组合

--求每个部门不同职位的平均工资

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

select avg(sal) from emp group by deptno,job having avg(sal)>1200

交叉连接(cross jcin)

什么是交叉连接:交加连接指的是两张或者多张表进行的笛卡儿积,

两张或多张表中每一行的数据任意组合的果。

语法:

select 查询内容 from table1 croos join table2

特点:总记录条数:table1记录条数*table2记录条数

总列数:table1列数+table2列数

自然连接

什么是自然连接:自然连接是关系表中相同名称的字段进行自动匹配产生的结果,会去重复的列

语法:select 查询内容

from table natura1 join table2

注意:1,关联的表中必须有相同名称的字段(字段名称相同字段数据类型相同)

2,查询结果中去掉重复的相同字段

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值