根据另一行中的值排除SQL查询中的行,同时保留单个部件ID的多个输出

问题描述

我有以下形式的机器输出数据:

atr2

并且我需要通过删除一些行来生成一个新表:

DATETIME            ID       VALUE
8-28-20 20:55:10    part1    13
8-28-20 20:56:60    part1    20
8-28-20 20:57:22    part1    25
8-28-20 20:59:39    part2    9
8-28-20 21:10:55    part3    33
8-28-20 21:14:30    part1    14

机器有时每次运行都会收集多个VALUE,但是我只需要最后一个(它是累积的)。但是,每个班次我可能会多次运行相同的ID,并且并非不可能连续两次运行相同的ID。

仅当VALUE大于其上一行的VALUE时,sql才可能过滤出其中行ID等于其上一行的ID的所有行吗?

这里也发布了一些类似的Q,但是它们都会导致对行进行分组并获得最大值,但是每个时间段我只会为每个ID捕获一次运行。

解决方法

更为通用,并作为获得没有特定OLAP功能的会话ID的示例:

WITH
-- your input
input(dttm,id,value) AS (
          SELECT TIMESTAMP '2020-08-28 20:55:10','part1',13
UNION ALL SELECT TIMESTAMP '2020-08-28 20:56:60',20
UNION ALL SELECT TIMESTAMP '2020-08-28 20:57:22',25
UNION ALL SELECT TIMESTAMP '2020-08-28 20:59:39','part2',9
UNION ALL SELECT TIMESTAMP '2020-08-28 21:10:55','part3',33
UNION ALL SELECT TIMESTAMP '2020-08-28 21:14:30',14
),-- add a counter that is at 1 whenever the id changes over time
with_chg AS (
  SELECT
    CASE 
      WHEN LAG(id) OVER(ORDER BY dttm) <> id THEN 1
      ELSE 0
    END AS chg_count,*
  FROM input
),-- use the running sum of that change counter to get a session id
with_session AS (
  SELECT
    SUM(chg_count) OVER(ORDER BY dttm) AS session_id,dttm,value
  FROM with_chg
),-- partition by the session id,order by datetime descending to get
-- the row number of 1 for the right row
with_rownum AS (
  SELECT
    ROW_NUMBER() OVER(PARTITION BY session_id ORDER BY dttm DESC) AS rownum,value
  FROM with_session
)
-- finally,filter by row number 1 and order back by datetime
SELECT
  dttm,value
FROM with_rownum
WHERE rownum = 1
ORDER BY 1
;
-- out         dttm         |  id   | value 
-- out ---------------------+-------+-------
-- out  2020-08-28 20:57:22 | part1 |    25
-- out  2020-08-28 20:59:39 | part2 |     9
-- out  2020-08-28 21:10:55 | part3 |    33
-- out  2020-08-28 21:14:30 | part1 |    14
,

您可以尝试以下操作-使用row_number()

select * from
(
select *,row_number() over(partition by dateadd(hour,datediff(hour,DATETIME),0),id order by DATETIME desc) as rn
from tablename
)A where rn=1
,

您似乎想要id更改且值增加的行:

select t.*
from (select t.*,lead(id) over (order by datetime) as next_id,lead(value) over (order by datetime) as next_value
      from t
     ) t
where next_id is null or next_id <> id or
      (next_id = id and next_value < value)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...