我有这样的查询
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"进行不必要的过滤。列。
答案 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