简体   繁体   English

从当前月份开始按月从mysql表中获取值的总和

[英]get sum of values from mysql table by month starting current month

Hi i currently have two tables, one has daily entries and other gets the total of those and stores monthly values. 嗨,我目前有两个表,一个具有每日条目,另一个具有这些条目的总数并存储每月值。

I'm able to get totals of each month and year with below query, but what i'd like to do is only get the months where month is greater than and equal to current month. 我可以使用下面的查询获取每个月和一年的总数,但是我想做的只是获取月份大于等于当前月份的月份。 btw date column is in date format (yyyy-mm-dd) btw日期列采用日期格式(yyyy-mm-dd)

$revbyMonth = $conn->prepare("SELECT EXTRACT(MONTH FROM date) as month, EXTRACT(YEAR FROM date) as year, SUM(rev) as total FROM {$tempName} GROUP BY year, month"); 

You want to add a where clause immediately after the from clause. 您要在from子句之后立即添加where子句。 I think this will work for you. 我认为这对您有用。 If the date has no time component: 如果日期没有时间部分:

where date > date_sub(curdate(), interval day(curdate()) day)

The expression date_sub(curdate(), interval day(curdate()) day) gets the last day of the previous month. 表达式date_sub(curdate(), interval day(curdate()) day)获取上个月的最后一天。 If the dates have a time component: 如果日期具有时间成分:

where date >= date_sub(curdate(), interval day(curdate()) - 1 day)

should work. 应该管用。

Note: this is better than other methods that process date using functions, such as: 注意:这比使用函数处理date其他方法更好,例如:

where year(date) > year(curdate()) or
      (year(date) = year(curdate()) and month(date) >= month(curdate()) )

The use of the functions prevents MySQL from using an index on the date column. 使用函数会阻止MySQL在date列上使用索引。

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

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