一年中每个月的价值总和

时间:2014-12-06 03:27:50

标签: mysql

我想在MySQL中进行查询以获取一年中每个月的值的总和。

目前我有这样的事情:

SELECT
    e.rfc as RFC,
    SUM(f.total) AS Total,
    MONTH(f.fecha) as Mes 
FROM
    foo f 
INNER JOIN
    bar e 
        ON f.bar_id = e.id 
INNER JOIN
    baz u 
        ON e.baz_id = u.id 
WHERE
    u.id = 3 
    AND DATE(f.fecha) BETWEEN '2014-01-01' AND '2014-12-31' 
GROUP BY
    MONTH(f.fecha) 

但是在不存在的月份里,foo值没有显示出来。

我的结果就像是:

RFC             Total           Mes
AAA010101AAA    10556.000000    12
AAA010101BBB    1856.000000     11
AAA010101BBB    66262.896800    10
AAA010101BBB    990.090000      9
AAA010101BBB    73.000000       8
AAA010101BBB    1304761.620000  7

我想要的结果是:

RFC             Total           Mes
AAA010101AAA    10556.000000    12
AAA010101AAA    0.0             11
... (When no data it's available just return 0.0 for the month)
AAA010101AAA    0.0             1
AAA010101BBB    0.0             12
AAA010101BBB    1856.000000     11
AAA010101BBB    66262.896800    10
AAA010101BBB    990.090000      9
AAA010101BBB    73.000000       8
AAA010101BBB    1304761.620000  7
AAA010101BBB    0.0             6
...
AAA010101BBB    0.0             1

我想填写图表,当没有可用于汇总的foo值时我需要零。

谢谢。

1 个答案:

答案 0 :(得分:1)

假设每个rfc每个月都有某些用户的数据,解决此问题的一种简单方法是使用条件聚合:

SELECT e.rfc as RFC,
       SUM(CASE WHEN u.id = 3 THEN f.total ELSE 0 END) AS Total,
       MONTH(f.fecha) as Mes 
FROM foo f INNER JOIN
     bar e 
     ON f.bar_id = e.id INNER JOIN
     baz u 
     ON e.baz_id = u.id 
WHERE DATE(f.fecha) BETWEEN '2014-01-01' AND '2014-12-31' 
GROUP BY MONTH(f.fecha) ;

如果这不起作用,您必须开始使用left join,并为每个rfc生成每个12个月的行。

编辑:

这是更痛苦的版本:

select sum(total), m.m
from (select distinct month(f.fecha) as m from foo where DATE(f.fecha) BETWEEN '2014-01-01' AND '2014-12-31' ) m left join
     foo f
     on month(f.fecha) = m.m left join
     bar e 
     ON f.bar_id = e.id left join
     baz u 
     ON e.baz_id = u.id and u.id = 3
group by m.m
order by m.m;

我不知道rfc值正在做什么。它来自任意行,并不属于查询。