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

后端 未结 2 904
没有蜡笔的小新
没有蜡笔的小新 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:52

    One more option to consider:

    Select Top 1000 * 
    From dbo.SomeTable 
    Where ....
    Order By NewID()
    

    but to be honest- like the previous answer more than this one. The question could be about performance..

    0 讨论(0)
  • 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                    
    
    0 讨论(0)
提交回复
热议问题