【问题标题】:Count and group by date should return 0 on no values按日期计数和分组应在没有值时返回 0
【发布时间】:2010-12-01 08:59:44
【问题描述】:

我正在尝试报告我们每天进行的采访次数。

所以我有一张采访表 比如

interviewid,staffid,date,cmets...

还有一个包含 2005 年到 2020 年所有日期的日期参考表。有一个名为 ref 的日期字段。

我的查询是:

SELECT count(*) as cnt FROM `interviews` 
right JOIN `dateRef` ON `date` = ref where type = 2 
and date > date_sub(now(),interval 7 day) group by date_format(ref,'%Y-%m-%d')

可以正常显示我们进行的采访,但在我们没有进行任何采访时显示...

例如这会返回:

1
2
4

但它应该返回

0
1
0
2
0
4
0

编辑:

显然问题来自 where 子句,因为如果我删除它,查询就可以正常工作...

【问题讨论】:

    标签: mysql count group-by


    【解决方案1】:

    尝试替换为

    right join
    

    改为

    left join
    

    另一个变化是

    where type = 2 
    

    where type = 2 OR type IS NULL
    

    所以最后的查询

    SELECT count(*) as cnt FROM `interviews` 
    right JOIN `dateRef` ON `date` = ref where (type = 2 OR type is null)
    and date > date_sub(now(),interval 7 day) group by date_format(ref,'%Y-%m-%d')
    

    【讨论】:

      【解决方案2】:

      如果我理解正确的话,type 是一个采访专栏。由于您使用的是右连接,因此您的联接表包含没有采访的日期的行,但这些行在 type 列中包含 NULL(以及 interviews 的任何其他列),因为这些日期在interviews 表。它们被您的WHERE 子句过滤掉了,该子句需要type=2,这就是COUNT 看不到它们的原因。

      你可以尝试WHERE (type=2 OR type IS NULL)之类的东西,至少如果interviews.type永远不是NULL

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-10
        • 2011-07-21
        • 2015-09-08
        • 1970-01-01
        相关资源
        最近更新 更多