IN子句和Group by

时间:2018-01-10 15:45:27

标签: postgresql

表:主题

ID   SUBJECT_NAME COLLEGE NAME  SYEAR
101   EA           AAA           2016
102   EA           AAA           2016
103   EL           BBB           2016
104   EP           CCC           2016

表:课程

SUBECT_ID  COURSE_NAME  SYEAR
104         EP           2016
101         EA           2016 

我必须从SUBJECTS表中选择符合以下条件的记录。

在Subjects表中多次出现但在COURSES表中没有条目的Subject_name。在上面的例子中,我必须只获得ID为102的EA。

select * 
from subjects 
where id not in ( select id from courses) 
  and ??

我不确定如何在此查询中包含聚合函数?

1 个答案:

答案 0 :(得分:0)

使用其他条件添加到WHERE子句。子查询

 SELECT subject_name FROM subjects HAVING count(*) > 1 GROUP BY subject_name

将返回在subjects表格中出现多次的subject_names,因此:

 SELECT id
 FROM subjects
 WHERE id NOT IN (SELECT id FROM courses)
     AND subject_name IN (SELECT subject_name FROM subjects HAVING count(*) > 1 GROUP BY subject_name)

您也可以执行此窗口功能:

 SELECT id
 FROM (SELECT id, COUNT(*) OVER (PARTITION BY subject_name) as subject_name_count FROM subjects) t1
 WHERE subject_name_count > 1
     AND id NOT IN (SELECT id FROM courses)