且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在MySQL中按时间跨度汇总数据

更新时间:2023-11-23 11:53:40

我有一个类似的问题:整理统计到时间块和它回答得非常好。本质上,答案是:

也许你可以使用DATE_FORMAT()函数和分组。这里有一个例子,希望你能适应你的确切需求。



pre $ SELECT
DATE_FORMAT(time,%H: %i),
SUM(bytesIn),
SUM(bytesOut)
FROM
stats
WHERE
time BETWEEN< start> AND< end>
GROUP BY
DATE_FORMAT(时间,%H:%i)

如果您的时间窗口覆盖超过一天,并使用示例格式,则来自不同日期的数据将汇总到每日时间的时段中。如果原始数据不完全符合小时,您可以使用%H:00将其平滑化。



感谢martin clayton提供的答案他提供了我。

Basically I want is to aggregate some values in a table according to a timespan.

What I do is, I take snapshots of a system every 15 minutes and I want to be able to draw some graph over a long period. Since the graphs get really confusing if too many points are shown (besides getting really slow to render) I want to reduce the number of points by aggregating multiple points into a single point by averaging over them.

For this I'd have to be able to group by buckets that can be defined by me (daily, weekly, monthly, yearly, ...) but so far all my experiments had no luck at all.

Is there some trick I can apply to do so?

I had a similar question: collating-stats-into-time-chunks and had it answered very well. In essence, the answer was:

Perhaps you can use the DATE_FORMAT() function, and grouping. Here's an example, hopefully you can adapt to your precise needs.

SELECT
    DATE_FORMAT( time, "%H:%i" ),
    SUM( bytesIn ),
    SUM( bytesOut )
FROM
    stats
WHERE
    time BETWEEN <start> AND <end>
GROUP BY
    DATE_FORMAT( time, "%H:%i" )

If your time window covers more than one day and you use the example format, data from different days will be aggregated into 'hour-of-day' buckets. If the raw data doesn't fall exactly on the hour, you can smooth it out by using "%H:00."

Thanks be to martin clayton for the answer he provided me.