簡體   English   中英

如何根據另一列的相同值計算一列的行數?

[英]How to count rows of a column by depending on same values of another column?

我在一個名為tbl_enrolments(id, student_id, semester_id, unit_id, date)的表中有五列。 這里我只需要根據這張表中的semester_id來計算相同unit_id的數量。 這就是我到目前為止所嘗試的方式..

SELECT e.unit_id, COUNT(e.unit_id) as count, 
       u.unit_title, 
       u.unit_name, 
       s.sem_name 
FROM tbl_enrolments e
INNER JOIN tbl_unit_of_study u
    ON e.unit_id = u.id
INNER JOIN tbl_semesters s
    ON e.semester_id = s.id
GROUP BY e.unit_id

在這里,這個查詢是從所有不同的semester_id計算所有相同unit_id 但我需要用相同的semester_id計算所有相同unit_id 我怎樣才能做到這一點?

我的桌子是這樣的:

表 - tbl_enrolments

檢查這是否是您正在尋找的東西以及它是否對您有幫助-

mysql> select semester_id, count(unit_id) from tbl_enrolments group by semester_id;
+-------------+----------------+
| semester_id | count(unit_id) |
+-------------+----------------+
|           2 |              5 |
|           1 |              8 |
|          12 |              2 |
+-------------+----------------+
3 rows in set (0.00 sec)

mysql> select semester_id, unit_id, count(unit_id) from tbl_enrolments group by semester_id, unit_id;
+-------------+---------+----------------+
| semester_id | unit_id | count(unit_id) |
+-------------+---------+----------------+
|           2 |       3 |              3 |
|           2 |       1 |              2 |
|           1 |       2 |              2 |
|           1 |       6 |              2 |
|           1 |       4 |              4 |
|          12 |       1 |              1 |
|          12 |       6 |              1 |
+-------------+---------+----------------+
7 rows in set (0.00 sec)

mysql> select semester_id, unit_id, count(unit_id) from tbl_enrolments group by semester_id, unit_id having semester_id = 2;
+-------------+---------+----------------+
| semester_id | unit_id | count(unit_id) |
+-------------+---------+----------------+
|           2 |       3 |              3 |
|           2 |       1 |              2 |
+-------------+---------+----------------+
2 rows in set (0.00 sec)

mysql> select semester_id, unit_id, count(unit_id) from tbl_enrolments group by semester_id, unit_id having semester_id = 2 and unit_id = 3;
+-------------+---------+----------------+
| semester_id | unit_id | count(unit_id) |
+-------------+---------+----------------+
|           2 |       3 |              3 |
+-------------+---------+----------------+
1 row in set (0.00 sec)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM