如何使用多个HAVING或类似内容?

时间:2018-10-08 23:44:42

标签: sql

有些麻烦,我只想向正在讲授3个或更多内部或外部课程(不一起)的老师展示。我想我的代码现在对2个内部和1个外部等非常满意。那么我如何确保它实际上将它们单独而不是一起计数?

SELECT t.pnr, t.tname
FROM teacher t
JOIN teaches s ON t.pnr = s.pnr
JOIN course c ON s.coursecode = c.coursecode
WHERE c.coursetype = 'intern' OR c.coursetype = 'extern'
GROUP BY t.pnr, t.tname
HAVING COUNT(c.coursetype) > 2

3 个答案:

答案 0 :(得分:2)

您可以使用条件汇总来获取教师教的内部和外部课程的数量:

SELECT t.pnr, t.tname,
   SUM(CASE WHEN c.coursetype = 'intern' THEN 1 ELSE 0 END) AS intcourses,
   SUM(CASE WHEN c.coursetype = 'extern' THEN 1 ELSE 0 END) AS extcourses
FROM teacher t
JOIN teaches s ON t.pnr = s.pnr
JOIN course c ON s.coursecode = c.coursecode
GROUP BY t.pnr, t.tname
HAVING intcourses > 2 or extcourses > 2

答案 1 :(得分:0)

您可以只计算where子句,而不要分组:

SELECT t.pnr, t.tname
FROM teacher t
WHERE (select count(*) from teaches s               
         JOIN course c ON c.coursecode = s.coursecode
          and c.coursetype='intern'
        where t.pnr = s.pnr) > 2
        OR
      (select count(*) from teaches s               
         JOIN course c ON c.coursecode = s.coursecode
          and c.coursetype='extern'
        where t.pnr = s.pnr) > 2   

答案 2 :(得分:0)

您使用having很有道理。您可以按照以下方式进行操作:

SELECT t.pnr, t.tname
FROM teacher t JOIN
     teaches s
     ON t.pnr = s.pnr JOIN
     course c
     ON s.coursecode = c.coursecode
WHERE c.coursetype IN ('intern', 'extern')
GROUP BY t.pnr, t.tname
HAVING SUM(CASE WHEN c.coursetype = 'intern' THEN 1 ELSE 0 END) >= 3 OR
       SUM(CASE WHEN c.coursetype = 'extern' THEN 1 ELSE 0 END) >= 3 ;