简体   繁体   English

如何计算 Postgresql 中具有相同时间戳的值的平均值?

[英]How to calculate average of values with the same timestamp in Postgresql?

i have the following table:我有下表:

date日期 value价值 Average平均
2021-04-07 18:00:00 2021-04-07 18:00:00 5 5
2021-04-07 18:00:00 2021-04-07 18:00:00 10 10
2021-04-07 18:02:00 2021-04-07 18:02:00 5 5
2021-04-07 18:02:00 2021-04-07 18:02:00 4 4
2021-04-07 18:03:00 2021-04-07 18:03:00 5 5
2021-04-07 18:03:00 2021-04-07 18:03:00 8 8

And i want to know how could i calculate the average of values with the same timestamp, like this:我想知道如何计算具有相同时间戳的值的平均值,如下所示:

date日期 value价值 Average平均
2021-04-07 18:00:00 2021-04-07 18:00:00 5 5 7,5 7,5
2021-04-07 18:00:00 2021-04-07 18:00:00 10 10 7,5 7,5
2021-04-07 18:02:00 2021-04-07 18:02:00 5 5 4,5 4,5
2021-04-07 18:02:00 2021-04-07 18:02:00 4 4 4,5 4,5
2021-04-07 18:03:00 2021-04-07 18:03:00 5 5 6,5 6,5
2021-04-07 18:03:00 2021-04-07 18:03:00 8 8 6,5 6,5

I'm also wondering if it would be easier to calculate the average on a separate table so they won't repeat because there is more than one row with the same timestamp.我还想知道在单独的表上计算平均值是否更容易,这样它们就不会重复,因为有不止一行具有相同的时间戳。 Hope someone can help me with this, thanks in advance.希望有人可以帮助我,在此先感谢。

In an internal select, obtain the avg with the group by date .在内部 select 中, group by dateavg Then join the records whose date is equal to the internal select date .然后join date等于内部 select date的记录。

SELECT t1.date,t2.value,t1.average 
FROM
 (SELECT date,AVG(Cast(value as Float)) as average
 FROM yourTable
 GROUP BY date) t1 JOIN yourTable t2 ON t1.date = t2.date

result: dbfiddle结果: dbfiddle

SELECT CAST(date AS DATE) as DateField, AVG(value) as avg_value
FROM MyTable
GROUP BY CAST(date AS DATE)

A simple query:一个简单的查询:

SELECT date, AVG(value) as avg_value FROM MyTable GROUP BY date

Use a window function:使用 window function:

select t.*,
       avg(value) over (partition by date) as timestamp_average
from t;

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

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