简体   繁体   English

在每个组下删除超过10个时间段的行

[英]Delete rows older than 10 time periods under each group

I have a table with 2 columns 我有一张两列的桌子

+---------+------------+
| symbol  | ts         |
+---------+------------+
|       1 | 1524696300 |
|       1 | 1524697200 |
|       1 | 1524698100 |
|       1 | 1524699000 |
|       1 | 1524699900 |
|       1 | 1524700800 |
|       1 | 1524701700 |
|       1 | 1524702600 |
|       1 | 1524703500 |
|       1 | 1524704400 |
|       1 | 1524705300 |
|       1 | 1524706200 |
|       2 | 1524697200 |
|       2 | 1524698100 |
|       2 | 1524699000 |
|       2 | 1524699900 |
+---------+------------+

I want to remove older than 10 rows under each group, each row is separated by 900 seconds and may have different timestamp values at the first and last row but the difference of 900 remains constant 我想删除每组下的10行以上,每行相隔900秒,第一行和最后一行可能有不同的时间戳记值,但900的差值保持不变

I tried this query 我试过这个查询

sqlite> select * from ohlc2 where ts < (select max(ts) from ohlc2) - 8100;

It only works on the table as a whole and not per group so if my item 1 and 2 have different starting and ending timestamps, the above method wont work 它只能在整个表上使用,而不能在每个组上使用,因此,如果我的项目1和2具有不同的开始和结束时间戳记,上述方法将无法工作

I am getting an error in this query which I tried now 我现在尝试此查询时遇到错误

sqlite> with m as (select symbol, max(ts) from ohlc2 group by symbol) select * from ohlc2 where symbol = m.symbol and ts < m.max - 8100;

How can I delete all rows older than 10 timestamps per group? 如何删除每个组中所有超过10个时间戳的行?

In SQLite, you can do this with a correlated subquery: 在SQLite中,您可以使用相关子查询来执行此操作:

delete ohlc2
    where ts < (select o2.ts
                from ohlc2 o2
                where o2.symbol = ohlc2.symbol
                order by o2.ts desc
                limit 1 offset 9
               );

I primarily work with MS SQL Server, so I don't know if SQLLite supports this syntax or not, but if this is valid syntax in SQLLite, then it should work: 我主要使用MS SQL Server,所以我不知道SQLLite是否支持此语法,但是如果这在SQLLite中是有效的语法,则它应该可以工作:

DELETE T1
FROM OHLC2 T1
INNER JOIN
    (
        SELECT
            symbol,
            MAX(ts) AS max_ts
        FROM
            OHLC2
    ) SQ ON SQ.symbol = T1.symbol AND SQ.max_ts > T1.ts + 8100

Should also work with a CTE as you have it, but you need to name your second column in the CTE with an alias. 应该也可以与CTE一起使用,但是您需要使用别名为CTE中的第二列命名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM