我的查詢有問題。我有兩個表,我想加入它們以根據第一個表上的主鍵獲取結果,但我缺少第一個表中的 1 個資料。
這是我的小提琴
如您所見,我缺少第 1 個月的“xx3”
我嘗試更改左右連接,但結果仍然相同。
所以如你所見,我必須將coalesce(sum(b.sd_qty),0) 設為總計,
如果沒有qty
,則將0
設置為預設值。
P粉2877263082024-02-26 09:49:06
您也應該將表格交叉連接到不同的日期:
SELECT a.item_code, COALESCE(SUM(b.sd_qty), 0) total, DATE_FORMAT(d.sd_date, '%m-%Y') month_year FROM item a CROSS JOIN ( SELECT DISTINCT sd_date FROM sales_details WHERE sd_date >= '2020-04-01' - INTERVAL 3 MONTH AND sd_date < '2020-05-01' ) d LEFT JOIN sales_details b ON a.item_code = b.item_code AND b.sd_date = d.sd_date GROUP BY month_year, a.item_code ORDER BY month_year, a.item_code;
或者,對於 MySql 8.0 ,使用遞歸 CTE 傳回您想要結果的所有月份的開始日期,可以交叉連接到表:
WITH RECURSIVE dates AS ( SELECT '2020-04-01' - INTERVAL 3 MONTH AS sd_date UNION ALL SELECT sd_date INTERVAL 1 MONTH FROM dates WHERE sd_date INTERVAL 1 MONTH < '2020-05-01' ) SELECT a.item_code, COALESCE(SUM(b.sd_qty), 0) total, DATE_FORMAT(d.sd_date, '%m-%Y') month_year FROM item a CROSS JOIN dates d LEFT JOIN sales_details b ON a.item_code = b.item_code AND DATE_FORMAT(b.sd_date, '%m-%Y') = DATE_FORMAT(d.sd_date, '%m-%Y') GROUP BY month_year, a.item_code ORDER BY month_year, a.item_code;
查看演示。