简体   繁体   English

每年每个月的价值总和

[英]sum of value of each month of year

I want to do a query in MySQL to get the sum of a value from every month on a year. 我想在MySQL中进行查询,以获取一年中每个月的值总和。

currently i have something like this: 目前我有这样的事情:

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) 

But in months where doesn't exist foo values are not showing. 但是在不存在的月份中,不会显示foo值。

My result atm it's something like: 我的结果atm是这样的:

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

My desired result are: 我想要的结果是:

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

I want to fill a chart and i need a zero when no foo values are available to sum. 我想填写图表,并且在没有foo值可用于求和时需要零。

Thank you. 谢谢。

Assuming you have data for some user in each month for each rfc , an easy way to fix this is using conditional aggregation: 假设您每个月都有每个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) ;

If this doesn't work, you have to start mucking around with left join and generating rows for the 12 months of the each for each rfc . 如果这不起作用,则必须开始进行left join联接处理,并为每个rfc的每个12个月生成行。

EDIT: 编辑:

Here is the more painful version: 这是更痛苦的版本:

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;

I don't know what the rfc value is doing. 我不知道rfc值在做什么。 It is coming from an arbitrary row and doesn't really belong in the query. 它来自任意行,实际上并不属于查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM