postgresql 将事件数据转换为时间序列

q35jwt9p  于 2023-03-29  发布在  PostgreSQL
关注(0)|答案(1)|浏览(146)

我有一张table

CODE  | start      | end
A     | 2023-03-03 |2023-03-04
A     | 2023-03-07 |2023-03-09 
B     | 2023-03-03 |2023-03-06
C     | 2023-03-02 | "null"

地点

  • code是事件代码,
  • 在事件激活时启动
  • end当事件恢复时,它也可以为空,这意味着事件尚未恢复

对于一个sql查询(可能在Postgres中是可执行的),我想转换成一个时间序列,例如,给定事件代码A,我得到如下内容

2023-03-03 1 
2023-03-06 0 
2023-03-07 1
2023-03-09 0

其中1表示激活,0表示恢复,类似于选择时间戳,时间序列中的值,其中代码=?(在示例中代码为A)

qv7cva1a

qv7cva1a1#

您可以使用UNION ALL组合针对表的两个查询,一个查询获取开始时间(并调用此event_date),第二个查询获取结束时间(并将其Map到event_date)。
以下返回您请求的结果(假设,根据其他评论,2023年3月6日是一个错字,应该是3月4日,就像您原始的表格一样):

-- create the original table
create table event_log (code varchar, start_date date, end_date date);
    
-- populate it with data
    insert into event_log values ('A', '2023-03-03'::date, '2023-03-04'::date);
    insert into event_log values ('A', '2023-03-07'::date, '2023-03-09'::date);
    insert into event_log values ('B', '2023-03-03'::date, '2023-03-06'::date);
    insert into event_log values ('C', '2023-03-02'::date, null);
    
-- use union all to retrieve 2 rows for each event
    SELECT * 
    FROM (
        SELECT code, start_date as event_date, 1 as activation
        FROM event_log
        UNION ALL
        SELECT code, end_date as event_date, 0 as activation
        FROM event_log
        WHERE end_date IS NOT NULL
    ) q 
    WHERE code = 'A'
    ORDER BY event_date;

我将把查询的主要部分 Package 成一个视图,这样您就可以根据需要查询数据,而不必担心细节。

CREATE OR REPLACE VIEW event_stream AS
    SELECT code, start_date as event_date, 1 as activation
        FROM event_log
    UNION ALL
    SELECT code, end_date as event_date, 0 as activation
        FROM event_log
        WHERE end_date IS NOT NULL
    ORDER BY event_date, code, activation desc;

然后要检索数据,需要查询视图,如下所示:

select * 
from event_stream
where code='A';

相关问题