[英]Query with group by date
我正在处理以下用户表,其中角色 = 2 表示用户是讲师,角色 = 3 表示用户是学生。
+--------+------+---------------+
| name | role | creation_date |
+--------+------+---------------+
| Tom | 2 | 2020-07-01 |
| Diana | 3 | 2020-07-01 |
| Rachel | 3 | 2020-07-01 |
| Michel | 3 | 2020-08-01 |
+--------+------+---------------+
我的目标是 select 所有教师和学生的总和值,按日期分组。 结果应如下所示:
+------------------+---------------+---------------+
| totalInstructors | totalStudents | creation_date |
+------------------+---------------+---------------+
| 1 | 2 | 2020-07-01 |
| 0 | 1 | 2020-08-01 |
+------------------+---------------+---------------+
在这种情况下,在 2020 年 7 月 1 日,我有 1 名教师和 2 名学生注册,而在 2020 年 8 月 1 日,我没有教师,我有 1 名学生注册。
我的问题是我在设置此查询时遇到困难,如果有人可以帮助我,非常感谢!
使用条件聚合:
SELECT
creation_date,
COUNT(CASE WHEN role = 2 THEN 1 END) AS totalInstructors,
COUNT(CASE WHEN role = 3 THEN 1 END) AS totalStudents
FROM yourTable
GROUP BY
creation_date;
您需要使用 case 语句进行计数,如下所示
select count(case when role=2 then 1 end) as totalInstructors
,count(case when role=3 then 1 end) as totalStudents
,creation_date
from tbl
group by creation_date
一个简单的 GRoupBY 和 SUM 有帮助
这行得通。 因为同情角色 = 2 在星期二返回 1,如果为假则返回 0
CREATE TABLE table1 ( `name` VARCHAR(6), `role` INTEGER, `creation_date` VARCHAR(10) ); INSERT INTO table1 (`name`, `role`, `creation_date`) VALUES ('Tom', '2', '2020-07-01'), ('Diana', '3', '2020-07-01'), ('Rachel', '3', '2020-07-01'), ('Michel', '3', '2020-08-01');
SELECT SUM(`role` = 2) totalInstructors, SUM(`role` = 3) totalStudents, `creation_date` FROM table1 GROUP BY `creation_date` ORDER BY `creation_date`
总教员 | 学生总数 | 创建日期 ---------------: | ------------: |:------------ 1 | 2 | 2020-07-01 0 | 1 | 2020-08-01
db<> 在这里摆弄
请使用以下查询,
select
case when role = 2 then count(1) end as totalInstructors,
case when role = 3 then count(1) end as totalStudents,
creation_date
from table_name
group by creation_date;
您可以使用COALESCE()
将 null 替换为 0
select COALESCE(totalInstructors, 0) as totalInstructors, COALESCE(totalStudents, 0) as totalStudents,creation_date
from
(select
case when role = 2 then count(1) end as totalInstructors,
case when role = 3 then count(1) end as totalStudents,
creation_date
from table_name
group by creation_date) qry;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.