user2881063
user2881063

Reputation: 1059

How to count at specific date range in mysql

I have created this mysql code to count at only specific date range, i dumped the output of my mysql code and here it is:

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')

But this outputs same count for each month, in which i confirmed that february and march has zero counts. What am I missing here?

Upvotes: 2

Views: 5913

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1269443

COUNT() counts non-null values. You can fix your code by using sum() instead. You can also simplify it by removing the if statements:

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';

In MySQL, a boolean result is treated as 0 for "false" and 1 for "true". This is a great convenience and allows you to use sum() to count the number of matches.

Note that I also removed the single quotes around the column names. Single quotes should be used for string and date constants, not for identifiers.

EDIT:

You can have this query run faster by using an index on q.date_emailed. However, I don't think the index will be used because of the date() function. You can fix this by changing the logic:

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';

Upvotes: 5

Niels
Niels

Reputation: 49909

You should use SUM instead of COUNT if you want to SUM up the 0 and 1.

The COUNT will COUNT the number of row, the SUM will sum up the values.

Upvotes: 2

Related Questions