使用WHERE x = 1时,如何将记录计数为“0”,其值为“0”

时间:2013-04-09 09:00:20

标签: mysql count where-clause

我有一个如下所示的表结构:

http://imgur.com/DswITVz

我有一个完美的查询,可以计算过去30天每天记录的记录数。它看起来像这样:

SELECT DATE(timestamp) AS date, COUNT(id) AS emails FROM 'emails WHERE timestamp >= now() - interval 1 month GROUP BY DATE(timestamp)

这输出以下内容非常好:

http://imgur.com/QkwTgiD

然而,接下来的事情对我来说似乎太难以想象了。现在我想计算过去30天每天有多少条记录,但仅限于时事通讯= 1。

我试图将WHERE语句看起来像这样:

SELECT DATE(timestamp) AS date, COUNT(*) AS emails, nyhedsbrev FROM emails WHERE timestamp >= now() - interval 1 month AND nyhedsbrev = 1 GROUP BY DATE(timestamp)

......并输出以下内容:

http://imgur.com/kIVKYjc

问题是,它省略了newsletter = 0的记录,并且我无法将我的第一个查询与新的查询进行比较,因为日期不匹配。我知道那是因为我使用WHERE newsletter = 1。

除了省略记录之外,我想要一个只从该日期开始的“0”的查询。我怎样才能做到这一点?最终的查询应输出:

http://imgur.com/XlcovbN

3 个答案:

答案 0 :(得分:0)

可能最好获取日期列表,然后将其加入针对子查询的连接,以获得所需的计数。

像这样的东西

SELECT Sub1.date, Sub2.emails, IFNULL(Sub3.emails, 0)
FROM (SELECT DISTINCT DATE(timestamp) AS date
FROM emails 
WHERE timestamp >= now() - interval 1 month) Sub1
LEFT OUTER JOIN (SELECT DATE(timestamp) AS date, COUNT(id) AS emails 
FROM emails WHERE timestamp >= now() - interval 1 month 
GROUP BY DATE(timestamp)) Sub2
ON Sub2.date = Sub3.date
LEFT OUTER JOIN (SELECT DATE(timestamp) AS date, COUNT(*) AS emails 
FROM emails 
WHERE timestamp >= now() - interval 1 month AND nyhedsbrev = 1 
GROUP BY DATE(timestamp)) Sub3
ON Sub1.date = Sub3.date

(你可以优化其中的一个子选择,但我已完全完成它以使它明显如何工作)

答案 1 :(得分:0)

您应该只需使用SUM()IF()即可获得所需的输出:

SELECT 
    DATE(timestamp) AS date, 
    COUNT(*) AS emails,
    SUM(IF(nyhedsbrev > 0, 1, 0)) as nyhedsbrev_count
FROM 
    emails 
WHERE 
    timestamp >= now() - interval 1 month
GROUP BY 
    DATE(timestamp)

SQLFiddle DEMO

修改:您甚至可以简化它,因为它是布尔值,只需使用SUM(nyhedsbrev),但这要求nyhedsbrev < / strong> 01

SELECT 
    DATE(timestamp) AS date, 
    COUNT(*) AS emails,
    SUM(nyhedsbrev) as nyhedsbrev_count
FROM 
    emails 
WHERE 
    timestamp >= now() - interval 1 month
GROUP BY 
    DATE(timestamp)

enter image description here

答案 2 :(得分:0)

假设时事通讯是布尔值1/0,那么这可能会为您提供所需的表格:

SELECT DATE(timestamp) AS date, COUNT(*) AS emails, nyhedsbrev 
FROM emails WHERE timestamp >= now() - interval 1 month GROUP BY DATE(timestamp),nyhedsbrev ;

只需添加另一个GROUP BY参数。