开发者

SQL Server - pull X random records per state

开发者 https://www.devze.com 2023-01-21 04:14 出处:网络
I have a table with records for each zip code in the united st开发者_如何学运维ates. For the purposes of displaying on a map, I need to select X random records per state. How would I go about doing th

I have a table with records for each zip code in the united st开发者_如何学运维ates. For the purposes of displaying on a map, I need to select X random records per state. How would I go about doing this?


Use:

WITH sample AS (
 SELECT t.*,
        ROW_NUMBER() OVER (PARTITION BY t.state
                               ORDER BY NEWID()) AS rank
   FROM ZIPCODES t)
SELECT s.*
  FROM sample s
 WHERE s.rank <= 5


SELECT * FROM ZipCodes ORDER BY NEWID()
0

精彩评论

暂无评论...
验证码 换一张
取 消