views:

29

answers:

2

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?

A: 
SELECT * FROM ZipCodes ORDER BY NEWID()
rupert0
Yeah, I know about newid. My question was how to pull random records for each state.
Chris
+4  A: 

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
OMG Ponies
This works quite well. Next question - if by some chance I am required to port this to MySQL - is there a more generally compatible way to form the query?
Chris
@Chris: Not as-is - MySQL doesn't have analytic/ranking function support.
OMG Ponies