问题
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