【问题标题】:How to fill in rows based on event type data如何根据事件类型数据填充行
【发布时间】:2020-09-04 20:05:14
【问题描述】:

所以我的表有 2 列:小时和客户 ID。每个顾客将有 2 行,一个对应于他/她进入商店的时间,一个对应于他/她离开商店的时间。使用这些数据,我想创建一个表,其中包含客户在商店中的每一个小时。例如,客户 X 在下午 1 点进入商店并在下午 5 点离开,因此将有 5 行(每小时 1 行),如下面的屏幕截图。

这是我现在的尝试:

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 

【问题讨论】:

  • Postgres 雪花。请仅标记您正在使用的一个数据库。
  • 如果客户的行数超过两行(例如,同一客户稍后返回商店)怎么办?
  • hour 列的数据类型是什么?
  • @GMB - 移除了雪花。小时是截断到最近的小时的时间戳
  • @GMB - 我们可以假设每个客户有 2 行(一个用于进入,一个用于退出),并且任何偏离的 customerID 都会被过滤掉。

标签: sql postgresql date select group-by


【解决方案1】:

假设:

  • 您正在运行 Postgres

  • 给定客户的表中总是正好有两行

  • hour 是类日期数据类型

然后一种选择是使用带有横向连接的generate_series(),如下所示:

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

客户 ID |小时 :------------ | :----------------- 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 是 | 2019-04-01 17:00:00 是 | 2019-04-01 18:00:00 是 | 2019-04-01 19:00:00

【讨论】:

    猜你喜欢
    • 2020-06-27
    • 2020-09-06
    • 2020-02-19
    • 2021-06-13
    • 1970-01-01
    • 2015-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多