【问题标题】:mysql 30 days range selection from column valuemysql 从列值中选择 30 天范围
【发布时间】:2013-11-14 06:46:26
【问题描述】:

每个客户都有自己的计费周期,从他们预定义的 billing_cycle_day 开始 30 天(比如 billing_cycle_day 是 10 月 7 日,那么他们的计费周期是 10 月 7 日到 11 月 6 日,依此类推。)

//kilowatts : double
//report_date : timestamp
//billing_cycle_day : int

SELECT sum(m.kilowatts), DAY(m.report_date),  d.billing_cycle_day
FROM reports_month m
join device d on m.mobile_number = d.mobile_number
where m.mobile_number = '123' 
GROUP BY DAY(m.report_date)

这给出了按天分组的所有可用记录每天的总千瓦使用量。现在我想要的是将其限制在每个客户的计费周期内......

我尝试过使用

SELECT sum(m.kilowatts), DAY(m.report_date),  d.billing_cycle_day
FROM reports_month m
join device d on m.mobile_number = d.mobile_number
where m.mobile_number = '123'
and DAY(m.report_date) BETWEEN d.billing_cycle_day AND d.billing_cycle_day + INTERVAL 30 DAY
GROUP BY DAY(m.report_date)

以及许多功能的变体。我是否必须使用存储过程,然后请帮助我。

但还是没有运气,,,, 任何帮助将不胜感激....

【问题讨论】:

    标签: php mysql sql function stored-procedures


    【解决方案1】:

    使用 DATE_ADD:http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-add

    SELECT sum(m.kilowatts), DAY(m.report_date),  d.billing_cycle_day
    FROM reports_month m
    JOIN device d on m.mobile_number = d.mobile_number
    WHERE m.mobile_number = '123'
    AND DAY(m.report_date) BETWEEN d.billing_cycle_day AND DATE_ADD(d.billing_cycle_day, INTERVAL 30 DAY)
    GROUP BY DAY(m.report_date)
    

    【讨论】:

      【解决方案2】:

      将日期测试放在ON 子句中,因为它是两个表之间关系的一部分。并且不要在比较中使用 DAY() 函数,因为它只返回 13 表示 11 月 13 日的数字(询问 13 是否在 10 月 7 日和 11 月 7 日之间是什么意思?);你想比较整个日期。

      SELECT sum(m.kilowatts), DAY(m.report_date),  d.billing_cycle_day
      FROM reports_month m
      join device d
      on m.mobile_number = d.mobile_number
         and m.report_date BETWEEN d.billing_cycle_day AND d.billing_cycle_day + INTERVAL 30 DAY
      where m.mobile_number = '123'    
      GROUP BY DAY(m.report_date)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-04-09
        • 1970-01-01
        • 1970-01-01
        • 2017-10-06
        • 2020-03-29
        • 1970-01-01
        • 2014-12-13
        • 1970-01-01
        相关资源
        最近更新 更多