GROUPBY的⽤法⽰例
GROUP表⽰分组,BY后⾯写字段名,就表⽰根据哪个字段进⾏分组,如果有⽤Excel⽐较多的话,GROUP BY⽐较类似Excel⾥⾯的透视表。
GROUP BY必须得配合聚合函数来⽤,分组之后你可以计数(COUNT),求和(SUM),求平均数(AVG)等
新建学校⽤户表:
CREATE TABLE `users` (
`id` bigint(15) NOT NULL AUTO_INCREMENT COMMENT '主键id ',
`school_id` bigint(15) NOT NULL COMMENT '学校id',
`user_name` varchar(8) NOT NULL COMMENT '姓名 ',
`user_price` decimal(13,3) DEFAULT NULL COMMENT '⼯资',
`user_state` varchar(5) DEFAULT '1' COMMENT '01学⽣,02⽼师,03班主任,04校长',group by的用法及原理详解
`create_time` datetime DEFAULT NULL COMMENT '创建时间 ',
`update_time` datetime DEFAULT NULL COMMENT '更新时间 ',
PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COMMENT='学校⽤户表';
1.分别按照年/⽉来统计⽤户⼊校的⼈数:
按年统计:
SELECT DATE_FORMAT(create_time,'%Y') as statistics_key,
count(*)  statistics_count
FROM
users
WHERE
create_time BETWEEN '2020-01-01 00:00:00' and '2021-03-30 00:00:00'
GROUP BY  statistics_key
按⽉统计:
SELECT DATE_FORMAT(create_time,'%Y-%m') as statistics_key,
count(*)  statistics_count
FROM users
WHERE
create_time BETWEEN '2020-01-01 00:00:00' and '2021-03-30 00:00:00'
GROUP BY  statistics_key
2.分别按照职位来统计⽤户摸个时间段⼊校的⼈数:
SELECT user_state as statistics_key,
count(*) as statistics_count
FROM
users
WHERE create_time BETWEEN '2020-01-01 00:00:00' and '2021-03-30 00:00:00'
GROUP BY statistics_key
注意:
where要放在group by前⾯
group by 后⾯加条件只能⽤having关键字

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。