在此查詢中,我們的目標是檢索過去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中文網其他相關文章!