MySQL - 选择日期范围内的行数

时间:2013-01-11 17:02:50

标签: mysql

我正在尝试选择特定日期范围之间存在的行序列,并计算具有该日期的行数。但是,可能有一个没有条目的日期,因此表中不存在。

该表包含具有以下数据的行:

2012-12-25
2012-12-25
2012-12-27
2012-12-27
2012-12-27
2012-12-28

根据这个问题,我创建了一个数字表来生成日期范围 MySQL how to fill missing dates in range?

我当前的查询在('SELECT * FROM wp_paypal_logs WHERE STR_TO_DATE(wp_paypal_logs.created, '%Y-%m-%d')附近失败

SELECT x.ts AS timestamp,
          COALESCE(COUNT(SELECT * FROM wp_paypal_logs WHERE STR_TO_DATE(wp_paypal_logs.created, '%Y-%m-%d' ) = x.ts), 0) AS cnt
     FROM (SELECT DATE_FORMAT(DATE_ADD('2012-12-25', INTERVAL n.id - 1 DAY), '%Y-%m-%d') AS ts
             FROM numbers n
            WHERE DATE_ADD('2012-12-25', INTERVAL n.id - 1 DAY) <= '2012-12-31') x
LEFT JOIN TABLE wp_paypal_logs ON STR_TO_DATE(wp_paypal_logs.created, '%Y-%m-%d') = x.ts

如何让我的结果集看起来像这样?

2012-12-25      2
2012-12-26      0
2012-12-27      3
2012-12-28      1

1 个答案:

答案 0 :(得分:1)

由于你是COALESCE,所以不确定是否需要LEFT JOIN部分,如果你依靠左连接表中可能有效的字段(因为它不会计算NULL):

SELECT 
   x.ts AS timestamp,
   COUNT(wp_paypal_logs.created) AS cnt
FROM (
    SELECT 
       DATE_FORMAT(DATE_ADD('2012-12-25', INTERVAL n.id - 1 DAY), '%Y-%m-%d') AS ts
    FROM numbers n
    WHERE DATE_ADD('2012-12-25', INTERVAL n.id - 1 DAY) <= '2012-12-31'
) x
LEFT JOIN wp_paypal_logs 
   ON STR_TO_DATE(wp_paypal_logs.created, '%Y-%m-%d') = x.ts
GROUP BY x.ts