1

我将简化这一点:

我有两个可以正常工作的 SQL 表达式:

第一的:

select count(*) as number1
 from T1
where DATE1>'2012-01-01' and DATE2<'2012-12-31'

结果:13

select  count(*) as number2 
from T1
where DATE3>DATE2 and CURDATE()>DATE2

结果:5

但是当我尝试在 GROUP BY 中插入这两个 COUNTS 时,我得到的结果总是 13 !!!

SELECT NAME,
 COUNT(case when DATE1>'2012-01-01' and DATE2<'2012-12-31' then 1 else 0 end) as number1, 
COUNT (case when (DATE3>DATE2 and CURDATE()>DATE2) then 1 else 0 end) as number 2
from T1

我得到的结果是:

NAME  NUMBER1  NUMBER2
A       5         5
B       4         4
C       4         4

但我应该得到:

NAME  NUMBER1  NUMBER2
A       5         4
B       4         0
C       4         1

这样列的总和为 13 和 5,就像前两个查询一样。我究竟做错了什么?谢谢

4

4 回答 4

4

COUNT(expression)不计入空表达式。您可以通过更改ELSE 0toELSE NULL或删除它来修改您的查询(ELSE NULL隐含在CASE表达式中):

SELECT name,
    COUNT(CASE WHEN date1 > '2012-01-01' AND date2 < '2012-12-31' 
              THEN 1 END
         ) AS number1, 
    COUNT(CASE WHEN date3 > date2 AND CURDATE() > date2 
              THEN 1 END
         ) AS number2
FROM T1 
GROUP BY name ;
于 2013-01-16T18:23:02.437 回答
1

尝试:

SELECT NAME,
(select count(*) from T1 where DATE1>'2012-01-01' and DATE2<'2012-12-31') AS number1,
(select count(*) from T1 where DATE3>DATE2 and CURDATE()>DATE2) AS number2
FROM T1
GROUP BY NAME
于 2013-01-16T18:05:32.843 回答
1

尝试这个:

SELECT name, 
       SUM(CASE WHEN DATE1>'2012-01-01' AND DATE2<'2012-12-31' THEN 1 ELSE 0 END) AS number1, 
       SUM(CASE WHEN (DATE3>DATE2 AND CURDATE()>DATE2) THEN 1 ELSE 0 END) AS number2 
FROM T1 GROUP BY name 
于 2013-01-16T18:21:24.867 回答
1

此处不要使用计数。使用 Sum。如果要使用计数,则将 null 放入 else 而不是 0

于 2013-01-16T18:03:35.937 回答