问题描述
我需要删除一行并根据ColumnName
的顺序保留下两行
╔═════╦═════════════╦═══════╦════════════╦════════╗
║ ID ║ Description ║ Value ║ Date ║ Number ║
╠═════╬═════════════╬═══════╬════════════╬════════╣
║ 0x0 ║ Desc ║ 100 ║ 2020/01/01 ║ 200 ║
║ 0x0 ║ Desc1 ║ 150 ║ 2020/01/01 ║ 201 ║
║ 0x0 ║ Desc2 ║ 75 ║ 2020/01/01 ║ 202 ║
║ 0x0 ║ Desc3 ║ 50 ║ 2020/01/01 ║ 500 ║
║ 0x0 ║ Desc4 ║ 55 ║ 2020/01/01 ║ 505 ║
║ 0x0 ║ Desc5 ║ 110 ║ 2020/01/01 ║ 507 ║
╚═════╩═════════════╩═══════╩════════════╩════════╝
例如,应删除行号202和507。
有可能吗?
解决方法
是的,您可以为行编号,然后将其删除。对此要非常小心。我当然不建议您经常使用这种技术。
with data as (
select *,row_number() over (order by Number) as rn from T
)
delete from data
where rn % 3 = 0;
请注意,row_number()
将从1而不是0开始。
如果要删除整个表格中三分之一的内容,可以使用row_number()
和一个可更新的CTE:
with cte as (
select row_number() over(order by number) rn
from mytable
)
delete from cte where rn % 3 = 0
row_number()
列举从1
开始的最小number
行;然后,外部查询将删除每三行。对于您的示例数据,这将删除具有number
和202
和507
的行。