Search code examples
sqlsql-serverwindow-functionssql-deletesql-server-2017

Random Rows Delete


I need to delete one row and keep the next two depending on order by 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 ║
╚═════╩═════════════╩═══════╩════════════╩════════╝

For example rows number 202 and 507 should deleted.
Is it possible?


Solution

  • Yes, you can number the rows and then delete them. Be very careful with this. I certainly don't recommend using this technique very often.

    with data as (
        select *, row_number() over (order by Number) as rn from T
    )
    delete from data
    where rn % 3 = 0;
    

    Be aware that row_number() will start with a value of 1 rather than 0.