dti70601 2015-07-19 18:13
浏览 104
已采纳

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

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)

$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"); 
  • 写回答

1条回答 默认 最新

  • dpno17028 2015-07-19 18:16
    关注

    You want to add a where clause immediately after the from clause. 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. 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:

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 机器学习训练相关模型
  • ¥15 Todesk 远程写代码 anaconda jupyter python3
  • ¥15 我的R语言提示去除连锁不平衡时clump_data报错,图片以下所示,卡了好几天了,苦恼不知道如何解决,有人帮我看看怎么解决吗?
  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制