Reputation: 75
I have five columns in a table called tbl_enrolments(id, student_id, semester_id, unit_id, date)
. Here I just need to count the number of same unit_id
according to same semester_id
from this table. This is how I've tried so far..
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
Here this query is counting all same unit_id
from all different semester_id
. But I need to count all same unit_id
with only same semester_id
. How can I do that?
My table is like this:
Upvotes: 1
Views: 978
Reputation: 349
Check if this is what you are looking for and if it helps you-
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)
Upvotes: 3