MySQL获得了一年中所有月份的统计数据

时间:2015-10-19 11:37:19

标签: mysql

我必须在一年中的所有月份进行SQL查询以获得公司的收入,但有些月份的表中没有记录。

我使用过这个查询:

SELECT COUNT(wp_dgl_stats.datetime_stamp)*wp_dgl_ads.price as incomes, MONTHNAME(wp_dgl_stats.datetime_stamp) as month
FROM wp_dgl_ads
INNER JOIN wp_dgl_stats ON wp_dgl_stats.id_ad = wp_dgl_ads.id
WHERE YEAR(wp_dgl_stats.datetime_stamp) = 2015
GROUP BY MONTHNAME(wp_dgl_stats.datetime_stamp)

我必须说wp_dgl_stats包含用户在网络的某些空间(广告显示)中发出的每次点击的记录,其中包含对广告的引用和日期时间戳。

此查询会准确返回收入和确切金额的月份。但我需要用0来获得剩下的几个月。

怎么可以这样做?

2 个答案:

答案 0 :(得分:5)

经过大量测试后,我得到了一个合适的解决方案。如果有人需要解释,我会在这里发布。

SELECT meses.month, CAST(COUNT(stats.id)*ads.precio AS UNSIGNED) as precio
            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
            ) as meses
            LEFT JOIN wp_dgl_stats stats ON meses.month = MONTH(stats.datetime_stamp)
            LEFT JOIN wp_dgl_ads ads ON stats.id_ad = ads.id AND YEAR(stats.datetime_stamp) = '2015'
            GROUP BY meses.month

因为我是一名西班牙语开发人员而且我需要有西班牙月份名称,所以我选择了月份编号,并使用PHP数组我们可以将月份数字转换为他的西班牙语名称。

如果有人有疑问,那就去做吧,我很乐意回答。

答案 1 :(得分:1)

你可以LEFT/RIGHT加入这几个月:

WITH monthnames AS (SELECT <something that returns a list of the month names> as monthname)
SELECT COALESCE(COUNT(wp_dgl_stats.datetime_stamp)*wp_dgl_ads.price, 0) as incomes, MONTHNAME(wp_dgl_stats.datetime_stamp) as month
FROM wp_dgl_ads
INNER JOIN wp_dgl_stats ON wp_dgl_stats.id_ad = wp_dgl_ads.id
RIGHT JOIN monthnames ON month = monthname
WHERE YEAR(wp_dgl_stats.datetime_stamp) = 2015
GROUP BY MONTHNAME(wp_dgl_stats.datetime_stamp)