SQL计数来自同一列,但不同的条件提取后来计算所有的结果

时间:2014-07-08 10:18:07

标签: sql

我正在尝试为不同的条件计算相同的列,但我也得到其他条件的后期计数结果。

对于这个sql:

select count(eqa.ID) as gold_yes  from EC_SECTION_ANSWER esa , EC_QUESTION_ANSWER eqa 
where esa.SC_NUMBER = 1079 and esa.ID = eqa.SC_ID and eqa.QU_ANSWER = 'Yes' and   eqa.QU_TYPE = 'abc';

我收到了输出gold_yes: 1

再次,如果我运行不同条件的SQL:

select count(eqa.ID) as gold_no  from EC_SECTION_ANSWER esa , EC_QUESTION_ANSWER eqa 
where esa.SC_NUMBER = 1079 and esa.ID = eqa.SC_ID and eqa.QU_ANSWER = 'No' and  eqa.QU_TYPE = 'abc';

我收到了输出gold_no: 0

现在如果运行sql合并:

select count(eqa.ID) as gold_yes ,count(eqa_2.ID) as gold_no  from EC_SECTION_ANSWER esa , EC_QUESTION_ANSWER eqa ,EC_SECTION_ANSWER esa_2 , EC_QUESTION_ANSWER eqa_2 
where esa.SC_NUMBER = 1079 and esa.ID = eqa.SC_ID and eqa.QU_ANSWER = 'Yes' and   eqa.QU_TYPE = 'abc'
and esa_2.SC_NUMBER = 1079 and esa_2.ID = eqa_2.SC_ID and eqa_2.QU_ANSWER = 'No' and eqa_2.QU_TYPE = 'abc'; 

我收到了输出:gold_yes: 0gold_no: 0。哪个应为gold_yes: 1gold_no: 0

任何人都可以指导我做错了什么。

先谢谢。

4 个答案:

答案 0 :(得分:1)

查询中的WHERE条件是问题:您不能同时拥有eqa.QU_ANSWER = 'Yes'eqa.QU_ANSWER = 'No',因此查询返回0行,值的计数为0行也是0。

您可以将条件更改为OR,或者您可以在COUNT中采用相同的条件,同时执行此操作还应将查询更改为使用显式JOIN而不是写入WHERE子句中的连接条件。

SELECT COUNT(CASE WHEN eqa.QU_ANSWER = 'Yes' THEN 1 ELSE NULL END) as gold_yes
     , COUNT(CASE WHEN eqa.QU_ANSWER = 'No' THEN 1 ELSE NULL END) as gold_no
FROM   EC_SECTION_ANSWER esa
       INNER JOIN EC_QUESTION_ANSWER eqa ON esa.ID = eqa.SC_ID
WHERE  esa.SC_NUMBER = 1079 
  AND  eqa.QU_TYPE = 'abc'; 

答案 1 :(得分:0)

where条款中的条件放入case并总结

select sum(case when esa.SC_NUMBER = 1079 
                     and eqa.QU_ANSWER = 'Yes' 
                     and eqa.QU_TYPE = 'abc'
                then 1
                else 0
           end) as gold_yes
...
from EC_SECTION_ANSWER esa
join EC_QUESTION_ANSWER eqa on esa.ID = eqa.SC_ID

答案 2 :(得分:0)

试试这个:

SELECT SUM(CASE WHEN (esa.SC_NUMBER = 1079 and 
                      esa.ID = eqa.SC_ID   and 
                      eqa.QU_ANSWER = 'Yes'and  
                      eqa.QU_TYPE = 'abc') 
           THEN 1 END) AS eqacount1
       SUM(CASE WHEN (esa.SC_NUMBER = 1079 and 
                      esa.ID = eqa.SC_ID   and
                      eqa.QU_ANSWER = 'No' and 
                      eqa.QU_TYPE = 'abc') 
          THEN 1 END)  AS eqacount2 
from EC_SECTION_ANSWER esa , EC_QUESTION_ANSWER eqa

: 它会工作检查出来

此致 Praveen Nelge

答案 3 :(得分:-1)

select count(case when eqa.QU_ANSWER='Yes' then eqa.ID end) as gold_yes,
       count(case when eqa.QU_ANSWER='No' then eqa.ID end) as gold_no
from   EC_SECTION_ANSWER esa , EC_QUESTION_ANSWER eqa 
where  esa.SC_NUMBER = 1079 and 
       esa.ID = eqa.SC_ID and 
       eqa.QU_TYPE = 'abc'