SQL 查询过去一年每个月销售额(含零销售额月份)
AI: '可以使用LEFT JOIN和COALESCE函数来实现: SELECT m.month, COALESCE(SUM(o.total), 0) AS sales FROM ( SELECT 1 AS month UNION SELECT 2 AS month UNION SELECT 3 AS month UNION SELECT 4 AS month UNION SELECT 5 AS month UNION SELECT 6 AS month UNION SELECT 7 AS month UNION SELECT 8 AS month UNION SELECT 9 AS month UNION SELECT 10 AS month UNION SELECT 11 AS month UNION SELECT 12 AS month ) m LEFT JOIN Orders o ON MONTH(o.created_at) = m.month AND o.created_at >= DATE_SUB(NOW(), INTERVAL 1 YEAR) GROUP BY m.month; '
原文地址: https://www.cveoy.top/t/topic/n5ds 著作权归作者所有。请勿转载和采集!