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?
Yeah, I know about newid. My question was how to pull random records for each state.
Chris
2010-10-22 16:07:20
+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
2010-10-22 16:05:50
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
2010-10-22 16:25:28
@Chris: Not as-is - MySQL doesn't have analytic/ranking function support.
OMG Ponies
2010-10-22 16:33:31