0

我有一个看起来像这样的表结构:

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

4

3 回答 3

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

(您可能可以优化其中的一个子选择,但我已经完整地完成了它以使其清楚它是如何工作的)

于 2013-04-09T09:09:02.163 回答
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 演示

编辑:您甚至可以简化它,因为它是一个布尔值,并且只需使用SUM(nyhedsbrev),但这nyhedsbrev需要 0or 1

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)

在此处输入图像描述

于 2013-04-09T09:09:11.377 回答
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 参数。

于 2013-04-09T09:10:49.557 回答