如何与SQL CASE语句

时间:2017-11-13 19:30:17

标签: sql

我有一个约100k记录的学生表,我有两种类型的数据:学生姓名和级别类型,选择值为primary,secondary,intermediate&大学

我想过滤掉这张表中的学生,该计数器的数量大于> 0,在所有级别的初级,次级,中级和大学

我能够使用以下查询找到每个级别中每个学生的总和

SELECT 
    student_id,
    SUM(CASE WHEN lev_type = 'primary' THEN 1 ELSE 0 END) AS primary,
    SUM(CASE WHEN lev_type = 'secondary' THEN 1 ELSE 0 END) AS secondary,
    SUM(CASE WHEN lev_type = 'intermediate' THEN 1 ELSE 0 END) AS intermediate,
    SUM(CASE WHEN level_type = 'university' THEN 1 ELSE 0 END) AS university 
FROM
    student_details
GROUP BY
    student_id

我得到一个结果(注意我的结果是92242行)

attendee_id     primary secondary   intermediate    uni
    student1    0        1                1          2
    student2    0        1                1          0
    student3    88       209              92         32
    student4    0        1                1          0
    student5    0        1                1          0

如何从此结果中过滤出student3?

2 个答案:

答案 0 :(得分:0)

HAVING可能会得到你想要的东西。例如:

SELECT student_id,
   sum(case when lev_type  = 'primary' then 1 else 0 end) as primary,
   sum(case when  lev_type  = 'secondary' then 1 else 0 end)  as secondary ,
   sum(case when  lev_type  = 'intermediate' then 1 else 0 end)  as intermediate ,
  sum(case when  level_type  = 'university' then 1 else 0 end) as university 
from student_details
group by student_id
-- Put the criteria here by which you want to filter
having sum(case when lev_type  = 'primary' then 1 else 0 end) = 0
    and sum(case when  lev_type  = 'secondary' then 1 else 0 end) = 0
    and sum(case when  lev_type  = 'intermediate' then 1 else 0 end) = 0
    and sum(case when  level_type  = 'university' then 1 else 0 end) = 0

答案 1 :(得分:0)

您可以按如下方式添加where语句:

SELECT student_id,
      SUM(case when lev_type  = 'primary' then 1 else 0 end) as primary,
      SUM(case when lev_type  = 'secondary' then 1 else 0 end)  as secondary ,
      SUM(case when lev_type  = 'intermediate' then 1 else 0 end)  as intermediate ,
      SUM(case when lev_type  = 'university' then 1 else 0 end) as university 
 FROM student_details
 GROUP BY student_id
 WHERE primary = 0 OR secondary = 0 OR intermediate = 0 OR university  = 0