0

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

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

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

根据这个问题,我创建了一个数字表来生成日期范围 MySQL 如何填充范围内缺失的日期?

我当前的查询在附近失败('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
4

1 回答 1

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
于 2013-01-11T17:13:03.977 回答