从MySQL填充PHP销售表(包括空月)

时间:2016-02-08 17:46:55

标签: php mysql

我有这个查询,它按月返回销售额:

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尽可能地做,但在这种情况下,我不认为它可以帮助我,因为没有月份表或类似的东西。

我是否需要做一些粗略的For Loop计数到12并在数组中搜索月份和年份的匹配?我觉得我错过了一些明显,优雅的做法......

1 个答案:

答案 0 :(得分:1)

您可以使用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