2017-07-18 70 views
-1

我需要在對象寫入表的分鐘內只收集最後一個條目。在同一分鐘內存在多個時選擇最新時間戳

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 

Data希望

2017-07-18 08:08:49.000 EM45_PackagingLine 1 
2017-07-18 09:31:50.000 EM45_PackagingLine 1 

任何幫助都將是真棒。

+0

[不良習慣踢:使用舊樣式的JOIN(http://sqlblog.com/blogs/aaron_bertrand/archive/2009/10/08/bad-habits-to-kick-using-old -style-joins.aspx) - 在ANSI - ** 92 ** SQL標準中(** 25年*),舊式*逗號分隔的表*樣式列表已替換爲* proper * ANSI'JOIN'語法*前),其使用是不鼓勵的 –

+0

小時內的最後一項,你的意思是? – Greenspark

+0

[檢索每個組中的最後一條記錄]的可能重複(https://stackoverflow.com/questions/1313120/retrieving-the-last-record-in-each-group) –

回答

0

這將爲您的結果集添加一個row_number,它首先在小時長桶中對event_time_local進行分組,並將它們編號爲最早的數字。然後,它僅選擇那些在其桶中最新的行。

我不完全清楚你想要你的'桶'有多大 - 它看起來像一小時的樣本數據,但我不確定。只需調整Date邏輯即可提供適當大小的間隔,如果這不是您想要的。

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 
相關問題