在此查询中,我们的目标是检索过去 7 天的所有交易,确保即使没有销售记录的日子也会包含在结果中。我们利用结合两个单独查询的技术来实现此结果。
首先,我们使用嵌套 SELECT 语句枚举过去 7 天内的所有日期。此查询有效地生成了一个日期列表,作为我们交易数据的基础。
SELECT DATE_FORMAT(a.Date,'%Y-%m-%d') as purchase_date, '0' as amount FROM ( SELECT curdate() - INTERVAL (a.a + (10 * b.a) + (100 * c.a)) DAY as Date FROM (SELECT 0 AS a UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS a CROSS JOIN (SELECT 0 AS a UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS b CROSS JOIN (SELECT 0 AS a UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS c ) a WHERE a.Date BETWEEN NOW() - INTERVAL 7 DAY AND NOW()
接下来,我们将这个完整的日期列表与聚合交易表中的每日销售数据的查询结合起来。此连接确保我们包含记录的交易和没有活动的日期的空行。
LEFT JOIN ( SELECT DATE_FORMAT(purchase_date, '%Y-%m-%d') as purchase_date, COALESCE(SUM(amount), 0) AS amount FROM transactions WHERE purchase_date BETWEEN NOW() - INTERVAL 7 DAY AND NOW() AND vendor_id = 0 GROUP BY purchase_date )t2 ON t2.purchase_date = t1.purchase_date GROUP BY t1.purchase_date ORDER BY t1.purchase_date DESC
通过无缝集成这两个查询,我们有效地构建了一个按时间顺序列出指定范围内的所有日期的表,带有相应的销售数据或没有发生交易的零。
以上是如何在显示过去 7 天的每日事务的 MySQL 查询中包含空行?的详细内容。更多信息请关注PHP中文网其他相关文章!