当多个存在于同一分钟内时,选择最新时间戳

时间:2017-07-18 16:43:13

标签: sql-server timestamp

我只需要收集对象写入表中的最后一个条目。

AckedSink

返回数据

SELECT 
    A.event_time_local AS Datetime, 'PackagingLine' as TagName, 
    A.state_cd AS VALUE
FROM 
    util_log A, util_state B
WHERE 
    ent_id = 12 
    AND event_time_local BETWEEN '2017-07-18 07:00:00' AND '2017-07-18 15:00:00' 
    AND B.state_cd IN (0, 1, 3, 4)
    AND A.state_cd = b.state_cd

想要的数据

2017-07-18 08:08:35.000 EM45_PackagingLine  0
2017-07-18 08:08:49.000 EM45_PackagingLine  1
2017-07-18 09:31:30.000 EM45_PackagingLine  0
2017-07-18 09:31:38.000 EM45_PackagingLine  0
2017-07-18 09:31:50.000 EM45_PackagingLine  1

任何帮助都会很棒。

1 个答案:

答案 0 :(得分:0)

这会在您的结果集中添加一个row_number,它首先在一小时的存储桶中对event_time_local进行分组,并最早将它们编号为最新的。然后它只选择那些桶中最新的行。

我并不完全清楚你想要多大的水桶和#39;是 - 你的样本数据看起来像一个小时,但我不确定。只需调整日期逻辑即可提供适当大小的间隔,如果这不是您想要的。

WITH NumberedResultSet AS 
(
    SELECT 
        A.event_time_local AS Datetime, 'PackagingLine' as TagName, 
        A.state_cd AS VALUE
        , ROW_NUMBER() OVER (Partition By  DATEADD(hour, DATEDIFF(hour, 0, event_time_local), 0) Order By event_time_local desc) as rn
    FROM 
        util_log A, util_state B
    WHERE 
        ent_id = 12 
        AND event_time_local BETWEEN '2017-07-18 07:00:00' AND '2017-07-18 15:00:00' 
        AND B.state_cd IN (0, 1, 3, 4)
        AND A.state_cd = b.state_cd
)

SELECT
    *
FROM
    NumberedResultSet
WHERE 
    rn = 1