时间序列postgresql查询的交叉连接

时间:2018-06-07 13:28:03

标签: sql postgresql group-by

我有一个带有

项目的表格
Item_id,  Item_time,             Item_numbers
  1       2017-01-01 18:00:00       2
  2       2017-01-01 18:10:00       2
  3       2017-01-01 19:10:00       3

我希望按小时将项目分组一段特定时间(每天9到3之间),如果特定时间没有条目,那么它应该是0。

期望的输出:

            Item_time          Item_numbers
         2017-01-01 18:00:00       4
         2017-01-01 19:00:00       3 
         2017-01-01 20:00:00       0    



with hour_items as (select date_trunc('hour', item_time) "hour",
avg(item_numbers) as value from items where item_id=2 and
fact_time::date= '2017-01-01' group by hour) select hour, value from
hour_items where EXTRACT(HOUR FROM hour) >= '9' and EXTRACT(HOUR FROM
> hour) < '15'.

上面的查询正确地对它们进行了分组,但是缺少小时的地方,没有条目。虽然它应该是一个带有0的条目,如所需的输出中所述。

1 个答案:

答案 0 :(得分:2)

这应该做。

我们获得所有不同的日子(CTE日期),然后我们为每个日期(CTE小时)生成小时数,最后我们将“按照我们的”基础加入我们的数据。

with sample_data as (
    select 1 as item_id, '2018-01-01 12:03:15'::timestamp as item_time, 2 as item_numbers
    union all
    select 2 as item_id, '2018-01-01 12:41:15'::timestamp as item_time, 1 as item_numbers
    union all
    select 3 as item_id, '2018-01-01 17:41:15'::timestamp as item_time, 2 as item_numbers
    union all
    select 4 as item_id, '2018-01-01 19:41:15'::timestamp as item_time, 2 as item_numbers
),
dates as (
    select distinct item_time::date
    from sample_data
),
hours as (
    select item_time + interval '1 hour' * a as hour
    from dates
    cross join generate_series(0,23) a
)
select h.hour, sum(coalesce(sd.item_numbers,0))
from hours h
left join sample_data sd on h.hour = date_trunc('hour', sd.item_time)
where extract(hour from hour) between 9 and 17
group by h.hour
order by h.hour