Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete Every Alternate Row in SQL

I need to clean up a table which has three columns, ID (uniqueidentifier), Observation (nvarchar), and Timestamp (datetimeoffset). The content is generated by two sensors at 1 hour interval, and the value of Observation is the same from the two sensors. My idea is to do a SELECT query such as

SELECT * FROM [Records] ORDER BY [Timestamp]

and then delete every alternate row.

I found this on SO how to delete every alternate row in access table, but doesn't really applies here as the ID is not Int but UID.

A sample of the data would look like:

enter image description here

like image 268
Jim Avatar asked Aug 13 '12 09:08

Jim


People also ask

How do you bulk delete rows in SQL?

There are a few ways to delete multiple rows in a table. If you wanted to delete a number of rows within a range, you can use the AND operator with the BETWEEN operator. DELETE FROM table_name WHERE column_name BETWEEN value 1 AND value 2; Another way to delete multiple rows is to use the IN operator.

How can we extract alternate rows from a table?

For this, simply select your range of cells and press the Ctrl+T keys together. Once you do this, the odd and even rows in your table will get shaded with different colors automatically.


1 Answers

If you are on SQL Server 2005 or later you can do something like this.

delete T
from (
       select row_number() over(order by [Timestamp]) as rn
       from YourTable
       where SomeColumn = @SomeValue
     ) T
where T.rn % 2 = 0
like image 165
Mikael Eriksson Avatar answered Oct 06 '22 14:10

Mikael Eriksson