分组与何处

时间:2014-12-03 14:36:53

标签: sql tsql

我想在一个带有基于datetime的where子句的数据集上进行分组,但我需要为Account表中不满足的任何用户返回0的计数where date要求。这是我的SQL语句:

select a.userid, count(c.codeentryid)
from [account] a
left join codesentered c
on a.userid = c.userid
where a.camp = 0 and c.entrydate > '2013-12-03 00:00:00'
group by a.userid
order by a.userid

目前,我对符合entrydate要求的所有用户都有统计数据,但如何将那些不满足此要求的用户归还为0?

3 个答案:

答案 0 :(得分:2)

您可以在join中添加条件。由于它是left outer join,因此它始终显示account的所有记录,并且只显示符合条件的codesentered的记录:

select a.userid, count(c.codeentryid)
from [account] a
left outer join codesentered c
on   a.userid = c.userid
/* here */ and  c.entrydate > '2013-12-03 00:00:00'
where a.camp = 0 
group by a.userid
order by a.userid

答案 1 :(得分:1)

当您使用left join时, second 表中的所有条件都应该进入on子句。否则,外连接将成为内连接。所以,试试这个:

select a.userid, count(c.codeentryid)
from [account] a left join
     codesentered c
     on a.userid = c.userid and c.entrydate > '2013-12-03 00:00:00'
where a.camp = 0 
group by a.userid
order by a.userid;

on子句中第一个表的条件基本上被忽略。即使left join子句的计算结果为false或onNULL也会返回第一个表中的所有行。

答案 2 :(得分:0)

这样的事可能。使用一些样本数据进行测试会更容易。

select a.userid, SUM(CASE WHEN c.entrydate > '2013-12-03 00:00:00' THEN 1 ELSE 0 END)
from [account] a
left join codesentered c
on a.userid = c.userid
where a.camp = 0 
group by a.userid
order by a.userid