时间戳表中持续时间的SQlite视图

7tofc5zh  于 2023-04-06  发布在  SQLite
关注(0)|答案(1)|浏览(193)

我有一个SQLite3表,它具有以下模式:

CREATE TABLE IF NOT EXISTS automationProcessLog (
    id integer PRIMARY KEY,
    timestamp text NOT NULL,    -- expected format yyyy-MM-dd hh:mm:ss.ssssss+ZZ:ZZ
    month_day text GENERATED ALWAYS AS (substr(timestamp, 6, 2) || '-' || substr(timestamp, 9, 2)) STORED,      -- expected format MM-dd
    hour integer GENERATED ALWAYS AS (substr(timestamp, 12, 2)) STORED,
    minute integer GENERATED ALWAYS AS (substr(timestamp, 15, 2)) STORED,
    weekday text NOT NULL,
    sampleID text,
    carrierID text,
    nodeID text,
    IOnode text,    -- expected True/False
    nodeType string GENERATED ALWAYS AS (substr(nodeID, 1, instr(nodeID, '/')-1)) STORED,
    nodeNumberByType integer GENERATED ALWAYS AS (substr(nodeID, instr(nodeID, '/')+1, length(nodeID))) STORED,
    processStep text,
    data text,
    FOREIGN KEY(nodeID) REFERENCES nodes(nodeID)
)

此表包含自动化上节点(nodeID)之间由托架(carrierID)运输的样本(sampleID)的所有事件。托架一次只能运输一个样本。
我想创建一个视图,其中有sampleIDcarrierIDtimestamp(当样品被引入到自动化系统时)、nodeID(当样品被引入时)、timestamp(当样品被处理时)(即除了加载之外的任何东西)、nodeID(当样品被处理时)以及duration(从加载到处理)。

  • 当行具有IOnode = "True"processStep = "Processed"时,加载样本
  • 一个样品在到达最终目的地之前可能会在多个节点进行处理,有时甚至会在同一个节点重复处理。在这种情况下,duration仍然从样品加载到自动化设备上时开始计数。
  • 样品在卸载后可以重新引入自动化装置。duration将从样品的最后一次加载开始计数。

一些伪逻辑将选择sampleIDcarrierIDtimestamptimestamp_processed)和nodeIDnodeID_processedWHERE NOT (IOnode = "True" AND processStep = "Processed"),添加timestamptimestamp_loaded)和nodeIDnodeID_loaded),对于具有相同sampleIDcarrierID的行,具有最新的timestamp,其早于(小于)timestamp_processedWHERE (IOnode = "True" AND processStep = "Processed"),并且为此计算时间戳之间的duration
我一直在研究LAG函数以及像this one这样的问题的答案,但我还没有能够产生一些有效的东西。

nxagd54h

nxagd54h1#

您可以使用子查询或CTE来提取加载时间,使用lead()窗口函数也可以获得同一样本的下一次加载时间。
然后将其与主表联接以获得相应的处理步骤和持续时间。

WITH load_times AS (
    SELECT sampleID, timestamp as timestamp_loaded, nodeID as nodeID_loaded, 
           lead(timestamp,1,'2999-12-31') OVER (PARTITION BY sampleID ORDER BY timestamp) as next_load
    FROM automationProcessLog 
    WHERE IOnode = 'True' and processStep = 'Processed'
)
SELECT sampleID, carrierID, timestamp as timestamp_processed, nodeID as nodeID_processed, 
       timestamp_loaded, nodeID_loaded, 
       (unixepoch(timestamp_processed) - unixepoch(timestamp_loaded)) as duration
FROM automationProcessLog l 
JOIN load_times lt ON (l.sampleID = lt.sampleID AND l.timestamp BETWEEN lt.timestamp_loaded AND lt.next_load)
WHERE NOT (l.IOnode = 'True' and l.processStep = 'Processed')

相关问题