How to fill in rows based on event type data

我的未来我决定 提交于 2020-07-09 11:54:09

问题


So my table has 2 columns: hour and customerID. Every customer will have 2 rows, one corresponding to hour that he/she came into the store, and one corresponding to hour that he/she left the store. With this data, I want to create a table that has every hour that a customer has been in the store. For example, a customer X entered the store at 1PM and left at 5PM, so there would be 5 rows (1 for each hour) like the screenshot below.

Here's my attempt that's now:

select
    hour
    ,first_value(customer_id) over (partition by customer_id order by hour rows between unbounded preceding and current row) as customer_id
FROM table 


回答1:


Assuming that:

  • you are running Postgres

  • a given customer always has exactly two rows in the table

  • hour is of a date-like datatype

Then one option is to use generate_series() with a lateral join, like so:

select t.customer_id, x.hour
from (
    select customer_id, min(hour) min_hour, max(hour) max_hour 
    from mytable 
    group by customer_id
) t
cross join lateral generate_series(min_hour, max_hour, '1 hour') x(hour)
order by t.customer_id, x.hour

Demo on DB Fiddlde:

customer_id | hour               
:---------- | :------------------
X           | 2019-04-01 13:00:00
X           | 2019-04-01 14:00:00
X           | 2019-04-01 15:00:00
X           | 2019-04-01 16:00:00
X           | 2019-04-01 17:00:00
Y           | 2019-04-01 17:00:00
Y           | 2019-04-01 18:00:00
Y           | 2019-04-01 19:00:00


来源:https://stackoverflow.com/questions/61879511/how-to-fill-in-rows-based-on-event-type-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!