随机行删除
Random Rows Delete
我需要删除一行并保留接下来的两行,具体取决于 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 开始。
如果要在整个table中删除三行中的一行,可以使用row_number()
和a,updatable 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
s 202
和 507
.
的行
我需要删除一行并保留接下来的两行,具体取决于 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 开始。
如果要在整个table中删除三行中的一行,可以使用row_number()
和a,updatable 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
s 202
和 507
.