简体   繁体   English

Mysql将给定日期范围内的每日总数汇总为每周总数

[英]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.目前,我的 db 表每天都有 dailTotal 值,我需要将这些分组为每周总计。

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() :所以,你可以使用yearweek()做你想做的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.您可以查看mode参数来控制星期是从星期日还是星期一开始,以及一年中的第一周是什么时候。 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.没有模式说:“一年的第一周从 1 月 1 日开始”,尽管您可以为此目的加入逻辑。

Note: If startTime has a time component, I am guessing you want:注意:如果startTime有一个时间组件,我猜你想要:

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 1- MySQL 版本支持聚合函数

2- Your field is of date type 2- 您的字段是日期类型

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

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