SQL Server - pull X random records per state

时光怂恿深爱的人放手 提交于 2020-01-03 08:14:06

问题


I have a table with records for each zip code in the united states. For the purposes of displaying on a map, I need to select X random records per state. How would I go about doing this?


回答1:


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



回答2:


SELECT * FROM ZipCodes ORDER BY NEWID()


来源:https://stackoverflow.com/questions/3998573/sql-server-pull-x-random-records-per-state

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!