Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select random values from each group, SQL

Tags:

sql

sql-server

I have a project through which I'm creating a game powered by a database.

The database has data entered like this:

(ID, Name) || (1, PhotoID),(1,PhotoID),(1,PhotoID),(2,PhotoID),(2,PhotoID) and so on. There are thousands of entries.

This is my current SQL statement:

$sql = "SELECT TOP 8 * FROM Image WHERE Hidden = '0' ORDER BY NEWID()";

But this can also produce results with matching IDs, where I need to have each result have a unique ID (that is I need one result from each group).

How can I change my query to grab one result from each group?

Thanks!

like image 549
chrsgrffth Avatar asked Feb 26 '26 12:02

chrsgrffth


1 Answers

Since ORDER BY NEWID() will result in tablescan anyway, you might use row_number() to isolate first in group:

; with randomizer as (
  select id,
         name,
         row_number() over (partition by id
                            order by newid()) rn
    from Image
   where hidden = 0
)
select top 8
       id,
       name
  from randomizer
 where rn = 1
-- Added by mellamokb's suggestion to allow groups to be randomized
order by newid()

Sql Fiddle playground thanks to mellamokb.

like image 151
Nikola Markovinović Avatar answered Mar 01 '26 02:03

Nikola Markovinović



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!