Case语句返回相同的值

时间:2014-09-04 17:44:42

标签: sql-server

我有以下案例陈述给我。

   SELECT schoolc,
   COUNT(CASE WHEN (subtestc) IN('ela','Math') AND tscrtypc ='A'THEN (ident) ELSE 0 END)AS       [total Students],
   COUNT(CASE WHEN (testscore)IN('A','P') AND subtestc IN('ela','Math')  AND tscrtypc ='A'THEN (ident) ELSE 0 END)AS [students above]

  FROM [dbo].[qw_star_testing_detail]
  WHERE subtestc IN('ela','Math')
  AND tscrtypc ='A'
  GROUP BY schoolc

它试图对上面的学生和学生进行两次单独的计算,但两者的价值相同。当我运行这个我得到1966这是正确的,但当我把它应用到我的情况时,我得到2362。我必须做一些简单的事情。

  select COUNT(ident),schoolc
  FROM [dbo].[qw_star_testing_detail]
  WHERE subtestc IN('ela','Math')
  AND tscrtypc ='A'
  AND testscore IN('A','P')
  GROUP BY schoolc
  ORDER BY schoolc

2 个答案:

答案 0 :(得分:0)

COUNT([column])返回结果集中指定列中具有非空值的行数。尝试这样的事情:

SELECT schoolc,
    SUM(CASE WHEN (subtestc) IN ('ela','Math') AND tscrtypc ='A'THEN 1 ELSE 0 END) AS [total Students],
    SUM(CASE WHEN (testscore)IN ('A','P') AND subtestc IN ('ela','Math') AND tscrtypc ='A'THEN 1 ELSE 0 END) AS [students above]
FROM [dbo].[qw_star_testing_detail]
WHERE subtestc IN('ela','Math')
AND tscrtypc ='A'
GROUP BY schoolc

答案 1 :(得分:0)

删除ELSE 0语句中的CASE部分,然后与CASE条件不匹配的记录将返回NULL,这将在汇总函数中排除。

  SELECT  schoolc
         ,COUNT(CASE WHEN (subtestc) IN('ela','Math') AND tscrtypc ='A'THEN (ident) END)AS       [total Students]
         ,COUNT(CASE WHEN (testscore)IN('A','P') AND subtestc IN('ela','Math')  AND tscrtypc ='A'THEN (ident) END)AS [students above]
  FROM [dbo].[qw_star_testing_detail]
  WHERE subtestc IN('ela','Math')
    AND tscrtypc ='A'
  GROUP BY schoolc