我在 presto 有一个表,有 2 列:date
和value
.
我想计算第二季度值的平均值,所以预期结果应该是:15。
我怎样才能做到这一点?
date value
2021-01-01 10
2021-01-30 20
2021-02-10 10
2021-04-01 20
2021-04-02 10
2021-07-10 20
您可以将月份除以 3 并按结果分组:
-- sample data
WITH dataset (date, value) AS (
VALUES (date '2021-01-01' , 10),
(date '2021-01-30' , 20),
(date '2021-02-10' , 10),
(date '2021-04-01' , 20),
(date '2021-04-02' , 10),
(date '2021-07-10', 20)
)
--query
SELECT avg(value)
FROM dataset
WHERE month(date) / 3 = 1
GROUP BY month(date) / 3
输出:
_col0 |
---|
15.0 |
使用四分之一功能:
with mytable as (
SELECT * FROM (
VALUES
(date '2021-01-01', 10),
(date '2021-01-30', 20),
(date '2021-02-10', 10),
(date '2021-04-01', 20),
(date '2021-04-02', 10),
(date '2021-07-10', 20)
) AS t (date, value)
)
select quarter(date) as qt, avg(value) as avg
from mytable
where quarter(date)=2
group by quarter(date)
结果:
qt avg
2 15.0