SQL Server:删除除最新的“n”个结果之外的所有结果
Posted
技术标签:
【中文标题】SQL Server:删除除最新的“n”个结果之外的所有结果【英文标题】:SQL Server: delete all but newest "n" results 【发布时间】:2021-02-26 16:57:56 【问题描述】:import pyodbc
def operations():
# server
server = 'DESKTOP-3KK3D6005'
database = 'my_database'
sql_driver = 'ODBC Driver 17 for SQL Server'
# connection
cnxn = pyodbc.connect(driver = sql_driver,
server = server,
database = database,
trusted_connection ='yes')
crsr = cnxn.cursor()
# delete oldest rows to minimize overhead.
crsr.execute("DELETE FROM my_table WHERE timestamp IN (SELECT timestamp FROM my_table ORDER BY timestamp ASC LIMIT 10)")
# query streamed data
maxval = crsr.execute("SELECT MAX(timestamp) FROM my_table").fetchval()
print(maxval)
我只需要流式传输的数据。我想删除除关于时间戳(纪元)的第 n 个最新行之外的所有内容,以尽量减少开销。
【问题讨论】:
LIMIT
不是 T-SQL 语法; T-SQL 使用TOP
。但是,如果您想省略前 10 个结果,则需要查看 OFFSET
。
【参考方案1】:
你可以使用这个语法
删除最旧的 10 个
delete from my_table where timestamp in (
select top 10 timestamp from my_table t order by timestamp
);
删除除 10 个最新的以外的所有内容
delete from my_table where timestamp not in (
select top 10 timestamp from my_table t order by timestamp desc
);
或者,我们可以从前 N 个中找到最小时间戳 并删除其余的
delete from my_table where timestamp < (
select min(timestamp) from
(select top 10 timestamp from my_table order by timestamp desc) m
);
【讨论】:
以上是关于SQL Server:删除除最新的“n”个结果之外的所有结果的主要内容,如果未能解决你的问题,请参考以下文章
使用 JQuery 从列表中删除除前 N 个元素之外的所有元素