How to request a random row in SQL?

前端 未结 29 3404
孤城傲影
孤城傲影 2020-11-21 06:45

How can I request a random row (or as close to truly random as is possible) in pure SQL?

29条回答
  •  萌比男神i
    2020-11-21 07:12

    For SQL Server 2005 and above, extending @GreyPanther's answer for the cases when num_value has not continuous values. This works too for cases when we have not evenly distributed datasets and when num_value is not a number but a unique identifier.

    WITH CTE_Table (SelRow, num_value) 
    AS 
    (
        SELECT ROW_NUMBER() OVER(ORDER BY ID) AS SelRow, num_value FROM table
    ) 
    
    SELECT * FROM table Where num_value = ( 
        SELECT TOP 1 num_value FROM CTE_Table  WHERE SelRow >= RAND() * (SELECT MAX(SelRow) FROM CTE_Table)
    )
    

提交回复
热议问题