选择过去 7 天的行,包括单个表中的空行
在 MySQL 数据库中,您希望从以下位置检索事务过去7天并计算每天的总销售额。但是,您希望确保即使特定日期没有可用数据,结果集中也会包含一个空行。
您已尝试解决此问题,但您的查询仅检索带有以下内容的日期:交易。为了达到预期的结果,您需要修改方法。
解决方案:
该解决方案涉及利用子查询生成过去 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如何检索最近7天的交易数据,包括没有交易的日子?的详细内容。更多信息请关注PHP中文网其他相关文章!