如何计算mysql中的特定日期范围

时间:2014-03-13 20:26:29

标签: mysql sql

我创建了这个mysql代码只计算特定的日期范围,我转储了我的mysql代码的输出,这里是:

SELECT COUNT(
                IF(
                        DATE(q.date_emailed) BETWEEN '2014-02-01' AND '2014-02-28',
                        1,
                        0
                    )
        ) AS 'Feb', 
        COUNT(
                    IF(
                        DATE(q.date_emailed) BETWEEN '2014-03-01' AND '2014-03-31',
                        1,
                        0
                    )
         ) AS 'March', 
         COUNT(
                    IF(
                        DATE(q.date_emailed) BETWEEN '2014-01-01' AND '2014-01-31',
                        1,
                        0
                    )
         ) AS 'Jan' 
        FROM
            database.quotes q
        WHERE (DATE(q.date_emailed) BETWEEN '2014-01-01' AND '2014-03-31')

但这会导致每个月的计数相同,其中我确认2月和3月的计数为零。我在这里错过了什么?

2 个答案:

答案 0 :(得分:3)

COUNT()计算非空值。您可以使用sum()来修复代码。您还可以通过删除if语句来简化它:

SELECT SUM(DATE(q.date_emailed) BETWEEN '2014-02-01' AND '2014-02-28') AS Feb, 
       SUM(DATE(q.date_emailed) BETWEEN '2014-03-01' AND '2014-03-31') AS March, 
       SUM(DATE(q.date_emailed) BETWEEN '2014-01-01' AND '2014-01-31') AS Jan
FROM database.quotes q
WHERE DATE(q.date_emailed) BETWEEN '2014-01-01' AND '2014-03-31';

在MySQL中,布尔结果被视为0表示“假”,1表示“真”。这非常方便,您可以使用sum()来计算匹配数。

请注意,我还删除了列名称周围的单引号。单引号应该用于字符串和日期常量,而不是标识符。

编辑:

您可以使用q.date_emailed上的索引更快地运行此查询。但是,由于date()函数,我认为不会使用该索引。您可以通过更改逻辑来解决此问题:

SELECT SUM(DATE(q.date_emailed) BETWEEN '2014-02-01' AND '2014-02-28') AS Feb, 
       SUM(DATE(q.date_emailed) BETWEEN '2014-03-01' AND '2014-03-31') AS March, 
       SUM(DATE(q.date_emailed) BETWEEN '2014-01-01' AND '2014-01-31') AS Jan
FROM database.quotes q
WHERE q.date_emailed >= '2014-01-01' AND
      q.date_emailed < '2014-04-01';

答案 1 :(得分:1)

如果要对0和1进行求和,则应使用SUM而不是COUNT。

COUNT将COUNT行数,SUM将总结值。