There is a table:
+-------------+----------+
|stud_group_id|subject_id|
+-------------+----------+
| 1g | 1s |
+-------------+----------+
| 1g | 2s |
+-------------+----------+
| 1g | 3s |
+-------------+----------+
| 2g | 1s |
+-------------+----------+
| 2g | 2s |
+-------------+----------+
| 3g | 1s |
+-------------+----------+
| 3g | 2s |
+-------------+----------+
| 3g | 4s |
+-------------+----------+
I need to select subject_id
learned by all stud_group_id
. I expect
+----------+
|subject_id|
+----------+
| 1s |
+----------+
| 2s |
+----------+
How can I do this? Thanks
Try this one:
select
subject_id,
count(distinct stud_group_id) as cnt
from
<your_table>
group by
subject_id
having cnt=(select count(distinct stud_group_id) from <your table>)
Something along the lines:
select count(stud_group_id) as num_learners_from_group, subject_id
from your_table group by subject_id
having num_learners_from_group =
(select count(*)
from stud_groups_table
where stud_groups_table.stud_group_id = your_table.stud_group_id
group by stud_groups_table.stud_group_id)
You can use having
clause as below :
select subject_id
from tab
group by subject_id
having count(distinct stud_group_id) = ( select count(distinct stud_group_id) from tab )
您尚未提及表名,因此使用TABLE_NAME作为占位符。
select distinct subject_id from TABLE_NAME group by stud_group_id, subject_id
Hope this works for you:
select subject_id
from mytable
group by subject_id
having count(*) = (select count(distinct stud_group_id) from mytable)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.