简体   繁体   中英

Mysql Sum daily totals into weekly totals for given date range

Currently my db table has dailTotal values for every single day, I need to get these grouped into weekly totals.

Is it possible to add the daily totals up into weekly totals and display a row each weekly total between the given date range.

Im not quite sure where to start with this one. My current query to get is by day is:

SELECT dailyTotal
FROM   energyUsage
WHERE  meterIdentifier = '1300011505120'
      AND startTime >= '2017-01-01 00:00:00'
      AND startTime <= '2017-12-31 00:00:00';

Weeks can be a bit ambiguous. One handy definition is the built-in definition. So, you can do what you want using yearweek() :

SELECT YEAREWEEK(startTime) as yyyyww, SUM(dailyTotal)
FROM  energyUsage
WHERE  meterIdentifier = '1300011505120' AND
       startTime >= '2017-01-01' AND
       startTime <= '2017-12-31'
GROUP BY yyyyww
ORDER BY yyyyww;

You can check out the mode argument to control whether weeks start on Sunday or Monday and when the first week of the year is. There is no mode that says: "the first week of the year starts on Jan 1st", although you could put in logic for that purpose.

Note: If startTime has a time component, I am guessing you want:

WHERE  meterIdentifier = '1300011505120' AND
       startTime >= '2017-01-01' AND
       startTime < '2018-01-01'  -- note the inequality

This should do it:

SELECT SUM(dailyTotal) AS weeklyTotal
FROM   energyUsage
WHERE  meterIdentifier = '1300011505120'
      AND startTime >= '2017-01-01 00:00:00'
      AND startTime <= '2017-12-31 00:00:00'
GROUP BY YEAR(startTime),WEEK(startTime);

You could use an aggregate function:

SELECT dailyTotal,
       sum(dailyTotal) over (partition by EXTRACT(MONTH FROM StartTime)) as MonTotal
FROM   energyUsage
WHERE  meterIdentifier = '1300011505120'
      AND startTime >= '2017-01-01 00:00:00'
      AND startTime <= '2017-12-31 00:00:00';

I am assuming a lot of things here but you get the idea.

1- The version of MySQL supports aggregated functions

2- Your field is of date type

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