SQL Server : how to select a fixed amount of rows (select every x-th value)

后端 未结 2 905
没有蜡笔的小新
没有蜡笔的小新 2021-01-06 09:22

A short description: I have a table with data that is updated over a certain time period. Now the problem is, that - depending on the nature of the sensor which sends the da

2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-06 09:58

    In essence, all you need to do to select the x-th value is retain all rows where the modulus of the rownumber divided by x is 0.

    WHERE rn % @x_thValues = 0
    

    Now to be able to use your ROW_NUMBER's result, you'll need to wrap the entire statement into in a subselect

    SELECT  *
    FROM    (
                SELECT  *
                        , rn = ROW_NUMBER() OVER (ORDER BY Value)
                FROM    DummyData
            ) d
    WHERE   rn % @x_thValues = 0                    
    

    Combined with a variable to what x-th values you need, you might use something like this testscript

    DECLARE @x_thValues INTEGER = 2
    
    ;WITH DummyData AS (SELECT * FROM (VALUES (1), (2), (3), (4)) v (Value))
    SELECT  *
    FROM    (
                SELECT  *
                        , rn = ROW_NUMBER() OVER (ORDER BY Value)
                FROM    DummyData
            ) d
    WHERE   rn % @x_thValues = 0                    
    

提交回复
热议问题