Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server - pull X random records per state

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?

like image 580
Chris Avatar asked Oct 22 '10 15:10

Chris


1 Answers

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
like image 52
OMG Ponies Avatar answered Sep 20 '22 16:09

OMG Ponies