Select n random rows from SQL Server table

前端 未结 16 794
陌清茗
陌清茗 2020-11-22 10:54

I\'ve got a SQL Server table with about 50,000 rows in it. I want to select about 5,000 of those rows at random. I\'ve thought of a complicated way, creating a temp table wi

16条回答
  •  有刺的猬
    2020-11-22 11:38

    I was using it in subquery and it returned me same rows in subquery

     SELECT  ID ,
                ( SELECT TOP 1
                            ImageURL
                  FROM      SubTable 
                  ORDER BY  NEWID()
                ) AS ImageURL,
                GETUTCDATE() ,
                1
        FROM    Mytable
    

    then i solved with including parent table variable in where

    SELECT  ID ,
                ( SELECT TOP 1
                            ImageURL
                  FROM      SubTable 
                  Where Mytable.ID>0
                  ORDER BY  NEWID()
                ) AS ImageURL,
                GETUTCDATE() ,
                1
        FROM    Mytable
    

    Note the where condtition

提交回复
热议问题