我的查询有问题。我有两个表,我想加入它们以根据第一个表上的主键获取结果,但我缺少第一个表中的 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;
查看演示。