简体   繁体   English

PostgreSQL:每天平均间隔

[英]Postgresql: Average for each day in interval

I have table that is structured like this: 我有这样的表结构:

item_id    first_observed    last_observed    price
1          2016-10-21        2016-10-27       121
1          2016-10-28        2016-10-31       145
2          2016-10-22        2016-10-28       135
2          2016-10-29        2016-10-30       169

What I want is to get the average price for every day. 我想要的是获取每天的平均价格。 I obviously cannot just group by first_observed or last_observed . 我显然不能只按first_observedlast_observed Does Postgres offer a smart way of doing this? Postgres是否提供执行此操作的明智方法?

The expected output would be like this: 预期的输出将是这样的:

date        avg(price)
2016-10-21  121
2016-10-22  128
2016-10-23  128
2016-10-24  128
2016-10-25  128
2016-10-26  128
2016-10-27  128
2016-10-28  140
2016-10-29  157
2016-10-30  157
2016-10-31  157

I could also be outputted like this (both are fine): 我也可以这样输出(都很好):

start       end         avg(price)
2016-10-21  2016-10-21  121
2016-10-22  2016-10-27  128
2016-10-28  2016-10-28  140
2016-10-29  2016-10-31  157
WITH ObserveDates (ObserveDate) AS (
    SELECT * FROM generate_series((SELECT MIN(first_observed) FROM T), (SELECT MAX(last_observed) FROM T), '1 days')
)
SELECT ObserveDate, AVG(Price)
FROM ObserveDates
JOIN T ON ObserveDate BETWEEN first_observed AND last_observed
GROUP BY ObserveDate
ORDER BY ObserveDate

demo:db<>fiddle 演示:分贝<>小提琴

generate_series allows you to expand date ranges: generate_series允许您扩展日期范围:

First step: 第一步:

SELECT 
    generate_series(first_observed, last_observed, interval '1 day')::date as observed, 
    AVG(price)::int as avg_price
FROM items
GROUP BY observed
ORDER BY observed
  1. expanding the date range 扩大日期范围
  2. grouping the dates for AVG aggregate 将AVG汇总的日期分组

Second step 第二步

SELECT 
    MIN(observed) as start,
    MAX(observed) as end,
    avg_price
FROM (
    -- <first step as subquery>
)s
GROUP BY avg_price
ORDER BY start
  1. Grouping by avg_price to get the MIN / MAX date for it 按avg_price分组以获取其MIN / MAX日期

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

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