简体   繁体   中英

mysql 30 days range selection from column value

Each customer have their own billing cycle of 30 days starting from their predefined billing_cycle_day (say billing_cycle_day is 7 th of October then their billing cycle would be 7th Oct to 6th Nov and so forth for every month..)

//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)

This gives the total kilowatt usage for each day for all available records grouped by day. Now what I want is to limit it to the billing cycle of each customer....

I tried using

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)

and lots of variations of the functions.Do I have to go for a stored proc then pls help me on that.

But still no luck,,,, Any help would be strongly appreciated....

Put the date test in the ON clause, since it's part of the relationship between the two tables. And don't use the DAY() function in the comparison, since it just returns the a number like 13 for November 13 (what does it mean to ask if 13 is between 7 October and 7 November?); you want to compare the whole 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
   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)

Use 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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