按季度计算平均值

Calculating averages by quarters

我有一个包含 2 列的 table:datevalue

我想计算第二季度的平均值,因此预期结果应该是: 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