MySQL计数范围条件

时间:2016-01-23 22:01:23

标签: mysql

我有这样的查询

select newscategory.CategoryName, count(distinct newsmain.id)
from newsmain join newscategory on 
newscategory.CategoryName = newsmain.Category 
group by CategoryName

并返回正确的结果,如下所示:

CategoryName  count(distinct newsmain.id)
Acupunctura   1
Neurologie    1
Test Category 2

" newsmain"表有一个" AppPublished" datetime字段和我尝试做的是为计数添加一个条件,根据是否" AppPublished"在两个日期时间变量的范围内。举个例子,我需要这样的结果:

CategoryName  count(distinct newsmain.id)
Acupunctura   0
Neurologie    0
Test Category 1

我是否需要创建子查询,或者是否有办法为此查询添加一些条件?

因为此查询中的任何添加条件导致对" CategoryName"进行不必要的过滤。列。

1 个答案:

答案 0 :(得分:1)

您可以使用CASE条件,例如

select newscategory.CategoryName, 
count(CASE WHEN AppPublished BETWEEN date1 and date2 THEN distinct newsmain.id END)
from newsmain join newscategory on 
newscategory.CategoryName = newsmain.Category 
group by CategoryName

(OR)喜欢这个

select newscategory.CategoryName, 
sum(CASE WHEN AppPublished BETWEEN date1 and date2 THEN 1 ELSE 0 END)
from newsmain join newscategory on 
newscategory.CategoryName = newsmain.Category 
group by CategoryName