【问题标题】:How to delete duplicates data that is in between two common value?如何删除两个公共值之间的重复数据?
【发布时间】:2022-01-21 23:04:10
【问题描述】:

如何根据常用值(开始和结束)删除重复数据

(时间是唯一的关键)

我的桌子是:

Time Data
10:24:11 Start
10:24:12 Result
10:24:13 Result
10:24:14 End
10:24:15 Start
10:24:16 Result
10:24:17 End

我想在 Start 和 End 之间获得 Data: Result,当重复发生时,它与 MAX(TIME) 一致。像这样

我想要的结果:

Time Data
10:24:11 Start
10:24:13 Result
10:24:14 End
10:24:15 Start
10:24:16 Result
10:24:17 End

我尝试重新排列数据,但似乎无法得到我想要的结果,有人可以就这个案例给出他们的建议吗?


更新

我最终没有使用@fredt 和@airliquide 建议的任何一种方法,因为我的HSQLDB 版本不支持该功能。

所以我所做的是,添加序列并使 Start = 1、Result = 2 和 End = 3。

Sequence Time Data Indicator
1 10:24:11 Start 1
2 10:24:12 Result 2
3 10:24:13 Result 2
4 10:24:14 End 3
5 10:24:15 Start 1
6 10:24:16 Result 2
7 10:24:17 End 3

因此,我利用指标和序列仅获取最新结果。这样如果前一行是 2(这是结果),则将其删除。

我遵循的指南: 来自:Is there a way to access the "previous row" value in a SELECT statement?

select t1.value - t2.value from table t1, table t2 
where t1.primaryKey = t2.primaryKey - 1

【问题讨论】:

    标签: sql hsqldb


    【解决方案1】:

    你可以用 SQL 过程来做这种事情。

    -- create the table with only two columns
    CREATE TABLE actions (attime TIME UNIQUE, data VARCHAR(10));
    
    -- drop the procedure if it exists
    DROP PROCEDURE del_duplicates IF EXISTS;
    
    create procedure del_duplicates()  MODIFIES SQL DATA begin atomic
    DECLARE last_time time(0) default null;
     for_loop:
     -- loop over the rows in order
     FOR SELECT * FROM actions ORDER BY attime DO
    
      -- each time 'Start' is found, clear the last_time variable
      IF data = 'Start' THEN
       SET last_time = NULL; 
       ITERATE for_loop;
      END IF;
    
      -- each time 'Result' is found, delete the row with previous time
      -- if last_time is null, no row is actually deleted 
      IF data = 'Result' THEN
       DELETE FROM actions WHERE attime = last_time;
       -- then store the latest time
       SET last_time = attime; 
       ITERATE for_loop;
      END IF;
            
    END FOR;        
    END
    

    你的数据必须都属于同一天,否则会出现无法区分的奇怪重叠。最好使用 TIMESTAMP 而不是 TIME。

    【讨论】:

      【解决方案2】:

      您好,第一种方法是使用引导功能如下

       select hour,status from (select *,lead(status,1) over ( order by hour) as lead
      from newtable)compare 
      where compare.lead <> status
      OR lead is null
      

      告诉我使用 postgres 引擎的预期效果。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多