SQL Server - 每个状态提取X个随机记录

时间:2010-10-22 15:51:02

标签: sql sql-server sql-server-2005 tsql greatest-n-per-group

我有一张表,其中包含美国各邮政编码的记录。为了在地图上显示,我需要为每个州选择X个随机记录。我该怎么做呢?

2 个答案:

答案 0 :(得分:12)

使用:

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

答案 1 :(得分:0)

SELECT * FROM ZipCodes ORDER BY NEWID()