PostgreSQL:每天平均间隔

时间:2019-01-11 10:14:15

标签: sql postgresql

我的表格结构如下:

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

我想要的是获取每天的平均价格。我显然不能仅仅按first_observedlast_observed分组。 Postgres是否提供执行此操作的明智方法?

预期输出如下:

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

我也可以这样输出(都很好):

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

demo:db<>fiddle

<driverClassName>net.sf.log4jdbc.DriverSpy</driverClassName> 允许您扩展日期范围:

第一步:

generate_series
  1. 扩大日期范围
  2. 分组AVG汇总的日期

第二步

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. 按avg_price分组以获取日期SELECT MIN(observed) as start, MAX(observed) as end, avg_price FROM ( -- <first step as subquery> )s GROUP BY avg_price ORDER BY start / MIN