Skip to content
Advertisement

Select random rows with no duplicates

I need to select a random amount of rows but also ensure that the rows don’t contain duplicate Image values:

ImgID   Image

1637    PM1371564839.jpg    
1638    PM1371564839.jpg    
1639    PM1371564840.jpg    
1640    PM1371564840.jpg    
1641    PM1371564840.jpg    
1642    PM1371564841.jpg    
1643    PM1371564842.jpg    
1644    PM1371564842.jpg    
1645    PM1371564842.jpg    
1646    PM1371564843.jpg    
1647    PM1371564843.jpg

I have done a – select top 25 percent * from Table order by newid(); This works for the random side of things but it brings back duplicate. I have tried a distinct but it doesnt like the order by part. Basically is there a better way to show just show a random 3 Images that are not duplicates.

Advertisement

Answer

looks like you have multiple images with different ImgID

maybe you want something like this to get unique images

SELECT TOP 25 PERCENT * FROM 
( 
  SELECT 
    max(imgID) imgID,  
    Image
  FROM [table]
  GROUP BY [Image]
) x
ORDER BY newid();
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement