Tag值从1变为2时获取Time_stamp,反之亦然

问题描述 投票:0回答:1

我有一个表包含两列名为 Time_stamp 和 PWPH_Pmp_2_FBSts 和表名称是 per_hour_log 我嵌入的屏幕截图示例

供参考。我写的查询如下

SELECT MAX(time_stamp) AS recent_datetime
FROM per_hour_log
WHERE PWPH_Pmp_2_FBSts = 2
AND time_stamp BETWEEN '2023-02-01 01:00:00' AND '2023-02-05 20:00:00'
AND EXISTS (
  SELECT 1 FROM per_hour_log
  WHERE PWPH_Pmp_2_FBSts = 1
  AND time_stamp BETWEEN '2023-02-01 01:00:00' AND '2023-02-05 20:00:00'
)

我期待的输出是

03-02-2023  05:00:00
02-02-2023  13:00:00 
sql sql-server database ssms
1个回答
0
投票

你可以试试这个查询

SELECT timestamp 
FROM 
   (SELECT timestamp, 
           (CASE 
                WHEN  PWPH_Pmp_2_FBSts <> LAG(PWPH_Pmp_2_FBSts) OVER (ORDER BY timestamp)             
                THEN 1
                ELSE 0
            END) data_changed
    FROM per_hour_log) data
WHERE data_changed = 1

看演示在这里

© www.soinside.com 2019 - 2024. All rights reserved.