我有这个查询,它按月返回销售额:
SELECT YEAR(txn_date) as 'year', MONTHNAME(txn_date) as 'month',
SUM(grand_total) as 'sales'
FROM transactions
WHERE YEAR(txn_date) BETWEEN '$last_year' AND '$this_year'
GROUP BY month
按月(包括没有销售额的月份)填充显示过去两年销售额的表格的好方法是什么?通常我喜欢让 SQL 尽可能多地执行,但在这种情况下,我认为它对我没有帮助,因为没有月表或类似的东西。
我是否必须执行一些计算到 12 的粗略 For 循环并在数组中搜索月份和年份的匹配项?我觉得我缺少一些明显的、优雅的方式来做这件事……
您可以使用 CROSS JOIN
轻松构建数月/数年的内联表:
SELECT y.`year` AS 'year', x.`month` AS 'month', SUM(grand_total) AS 'sales'
FROM (
SELECT 1 AS `month` 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 UNION ALL
SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12 ) AS x
CROSS JOIN (
SELECT 2015 AS ` year` UNION ALL SELECT 2016) AS y
LEFT JOIN transactions AS z ON x.`month` = MONTH(txn_date) AND
y.`year` = YEAR(txn_date)
GROUP BY x.`month`, y.`year`
Demo here