[英]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.