MySQL查询 - 间隔求和

时间:2016-08-03 20:03:06

标签: php html mysql sql

Hello Stack Overflow社区!

我的MySQL查询有点问题。我之后的是一个查询,它将从表中返回所有Project_Cost的总和,但我希望它在每个时间帧中将其拆分为不同的部分。对我而言,我希望它们每个月分开(例如:六月,七月,八月等所有费用)

我现在设置的方式是它以一个月的增量分割它们,但这是由当前日期确定的。所以基本上这只会在本月的第一天起作用,从那时起它就不准确了。

有人可以帮我编辑这个查询,以便它能告诉我我之后的内容吗?我已经测试了很多我已经看过的方法,但没有什么能给我提供我所追求的东西。

SELECT SUM(IF(DateSigned BETWEEN DATE(DATE_ADD(NOW(), INTERVAL -1 MONTH)) AND NOW(),Project_Cost,0)) AS A,
    SUM(IF(DateSigned BETWEEN DATE(DATE_ADD(NOW(), INTERVAL -2 MONTH)) AND DATE(DATE_ADD(NOW(), INTERVAL -1 MONTH)),Project_Cost,0)) AS B,
    SUM(IF(DateSigned BETWEEN DATE(DATE_ADD(NOW(), INTERVAL -3 MONTH)) AND DATE(DATE_ADD(NOW(), INTERVAL -2 MONTH)),Project_Cost,0)) AS C,
    SUM(IF(DateSigned BETWEEN DATE(DATE_ADD(NOW(), INTERVAL -4 MONTH)) AND DATE(DATE_ADD(NOW(), INTERVAL -3 MONTH)),Project_Cost,0)) AS D,
    SUM(IF(DateSigned BETWEEN DATE(DATE_ADD(NOW(), INTERVAL -5 MONTH)) AND DATE(DATE_ADD(NOW(), INTERVAL -4 MONTH)),Project_Cost,0)) AS E,
    SUM(IF(DateSigned BETWEEN DATE(DATE_ADD(NOW(), INTERVAL -6 MONTH)) AND DATE(DATE_ADD(NOW(), INTERVAL -5 MONTH)),Project_Cost,0)) AS F,
    SUM(IF(DateSigned BETWEEN DATE(DATE_ADD(NOW(), INTERVAL -7 MONTH)) AND DATE(DATE_ADD(NOW(), INTERVAL -6 MONTH)),Project_Cost,0)) AS G
    FROM project
    WHERE program = '1';

2 个答案:

答案 0 :(得分:0)

您可以使用YEAR(date)*12+MONTH(date)来比较月份:

SELECT SUM(IF(YEAR(DateSigned)*12+MONTH(DateSigned) = YEAR(Now())*12+MONTH(Now()),Project_Cost,0)) AS CurrentMonth,
       SUM(IF(YEAR(DateSigned)*12+MONTH(DateSigned) = YEAR(Now())*12+MONTH(Now())-1,Project_Cost,0)) AS PreviousMonth,
       SUM(IF(YEAR(DateSigned)*12+MONTH(DateSigned) = YEAR(Now())*12+MONTH(Now())-2,Project_Cost,0)) AS C
       /* etc... */
FROM   project
WHERE  program = '1'

答案 1 :(得分:0)

可能我不明白你的问题,但看起来是一个小组(年和月)

SELECT year(DateSigned), month(DateSigned), sum(Project_Cost)
from project 
WHERE program = '1'
Group By year(DateSigned), month(DateSigned)