如何在 Postgresql 中计算具有相同时间戳的平均值?
How to calculate average of values with the same timestamp in Postgresql?
我有以下 table:
date
value
Average
2021-04-07 18:00:00
5
2021-04-07 18:00:00
10
2021-04-07 18:02:00
5
2021-04-07 18:02:00
4
2021-04-07 18:03:00
5
2021-04-07 18:03:00
8
我想知道如何计算具有相同时间戳的值的平均值,如下所示:
date
value
Average
2021-04-07 18:00:00
5
7,5
2021-04-07 18:00:00
10
7,5
2021-04-07 18:02:00
5
4,5
2021-04-07 18:02:00
4
4,5
2021-04-07 18:03:00
5
6,5
2021-04-07 18:03:00
8
6,5
我也想知道在单独的 table 上计算平均值是否会更容易,这样它们就不会重复,因为有不止一行具有相同的时间戳。
希望有人能帮我解决这个问题,在此先感谢。
SELECT CAST(date AS DATE) as DateField, AVG(value) as avg_value
FROM MyTable
GROUP BY CAST(date AS DATE)
在内部 select 中,使用 group by date
获取 avg
。那么join
date
等于内部selectdate
.
的记录
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
结果:dbfiddle
一个简单的查询:
SELECT date, AVG(value) as avg_value FROM MyTable GROUP BY date
使用window函数:
select t.*,
avg(value) over (partition by date) as timestamp_average
from t;
我有以下 table:
date | value | Average |
---|---|---|
2021-04-07 18:00:00 | 5 | |
2021-04-07 18:00:00 | 10 | |
2021-04-07 18:02:00 | 5 | |
2021-04-07 18:02:00 | 4 | |
2021-04-07 18:03:00 | 5 | |
2021-04-07 18:03:00 | 8 |
我想知道如何计算具有相同时间戳的值的平均值,如下所示:
date | value | Average |
---|---|---|
2021-04-07 18:00:00 | 5 | 7,5 |
2021-04-07 18:00:00 | 10 | 7,5 |
2021-04-07 18:02:00 | 5 | 4,5 |
2021-04-07 18:02:00 | 4 | 4,5 |
2021-04-07 18:03:00 | 5 | 6,5 |
2021-04-07 18:03:00 | 8 | 6,5 |
我也想知道在单独的 table 上计算平均值是否会更容易,这样它们就不会重复,因为有不止一行具有相同的时间戳。 希望有人能帮我解决这个问题,在此先感谢。
SELECT CAST(date AS DATE) as DateField, AVG(value) as avg_value
FROM MyTable
GROUP BY CAST(date AS DATE)
在内部 select 中,使用 group by date
获取 avg
。那么join
date
等于内部selectdate
.
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
结果:dbfiddle
一个简单的查询:
SELECT date, AVG(value) as avg_value FROM MyTable GROUP BY date
使用window函数:
select t.*,
avg(value) over (partition by date) as timestamp_average
from t;