MS SQL Server选择没有重复项的随机行

时间:2013-06-18 19:56:33

标签: sql sql-server sql-server-2008

我需要选择随机数量的行,但也要确保行不包含重复的Image值:

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

我做了一个 - select top 25 percent * from Table order by newid();这适用于事物的随机方面,但它会带来重复。我尝试了一个独特的但它不喜欢按顺序排序。基本上有一种更好的方式来显示只显示一个不重复的随机3图像。

4 个答案:

答案 0 :(得分:2)

看起来你有多个具有不同ImgID的图像

也许你想要这样的东西来获得独特的图像

SELECT TOP 25 PERCENT * FROM 
( 
  SELECT 
    max(imgID) imgID,  
    Image
  FROM [table]
  GROUP BY [Image]
) x
ORDER BY newid();

答案 1 :(得分:1)

我会从以下内容开始:

SELECT TOP 25 PERCENT
 *
FROM
  (SELECT DISTINCT image FROM table) -- only unique image values
ORDER BY
 newid() -- random sort

请记住,他的查询有一些问题:

  • Subselect读取整个表并在其上生成DISTINCT(可能需要索引)。
  • 很难加入TABLE表中的其他列(没有PK会破坏DISTINCTSELECT

以上是上述查询的可读版本:

;WITH unique_images AS (
  SELECT DISTINCT image FROM TABLE
)
SELECT TOP 25 PERCENT
  *
FROM
  unique_images
ORDER BY
  new_id()

答案 2 :(得分:0)

Use Northwind
GO


select top 10 CustomerID , OrderID
from
(
select distinct CustomerID, OrderID from dbo.[Orders]
) as derived1

order by newid()

映射到你的:

select top 25 PERCENT ImgID , Image
from
(
select distinct ImgID , Image from dbo.[MyTable]
) as derived1

order by newid()

答案 3 :(得分:0)

这样就可以了:

SELECT TOP 3 ImgID, Image
FROM (SELECT DISTINCT ImgID, Image
      FROM #MyTABLE
      )sub
ORDER BY NEWID()

演示:SQL Fiddle