选择多个计数

时间:2013-11-07 01:49:55

标签: mysql

我的选择:

   SELECT DISTINCT

   (SELECT COUNT(*) 
   FROM t_table 
   WHERE year(date) BETWEEN '2013' AND '2013' AND month(date) BETWEEN '1' AND '12' AND date!=cad_em) as total1,

   (SELECT COUNT(*)
   FROM t_table
   WHERE year(date) BETWEEN '2013' AND '2013' AND month(date) BETWEEN '1' AND '12' AND date=cad_em ) as total2

   FROM t_table
   GROUP BY date

返回:

total1 | total2
1        4    

但我想回复约会 例:

date        | total1 | total2
2013-10     7          8
2013-11     1          4
2013-12     2          5

如何对我的示例显示相同的响应?

谢谢!

2 个答案:

答案 0 :(得分:1)

您可以使用条件求和来简化事情。此外,我不确定你的条件在哪里有意义,除非这些是参数 -

select
date,
sum( if(date = cad_em, 0, 1) ) as total1,
sum( if(date = cad_em, 1, 0) ) as total2
from
t_table
where year(date) = 2013 and month(date) between 1 and 12
group by date

答案 1 :(得分:0)

我想你想要这样的东西:

select max(`date`) as `date`, sum(`date` <> cad_em) as total1, sum(`date` = cad_em) as total2
from t_table
where year(`date`) = 2013;

您希望获得最大日期,但这只是猜测。