MYSQL學習筆記7: 聚合函式

HIK4RU44發表於2024-03-08

聚合函式

★所有的null值不參加聚合函式的計算


  • count 統計數量

  • max 最大值

  • min 最小值

  • avg 平均值

  • sum 求和


格式
select 聚合函式(欄位列表) from 表名
從workers表中查詢
#查詢記錄數量
select count(*) from workers;
#查詢id欄位不為null的記錄數量
select count(id) from workers
#因有一個age為null, null不參加聚合函式的運算, 所以比總數少1
select count(age) from workers;


重新建立表
create table workers(
    id int comment '編號',
    workNo varchar(10) comment '工號',
    name varchar(20) comment '姓名',
    gender char(1) comment '性別',
    age tinyint unsigned comment '年齡',
    idCard char(18) comment '身份證號',
    entryDate DATE comment '入職日期'
) comment '員工表';
插入資料
insert into workers values
    (1,'1','A','女',101,'100000000000000001','2024-03-08'),
    (2,'2','B','男',102,'100000000000000002','2024-03-08'),
    (3,'3','C','女',103,'100000000000000003','2024-03-08'),
    (4,'4','D','男',104,'100000000000000004','2024-03-08'),
    (5,'5','E','女',105,'100000000000000005','2024-03-08'),
    (6,'6','F','男',106,'100000000000000006','2024-03-08');


平均數
#計算平均年齡
select avg(age) as '平均年齡' from workers;


最大/最小值
select 
    max(age) as 'maxAge',
    min(age) as 'minAge' 
from workers;


求和
select sum(age) from workers;

相關文章