SQL SERVER - 选择不同的随机行数

时间:2013-11-08 15:01:29

标签: sql-server select distinct

我有以下查询,选择100个随机行。但是我还需要选择不同的名称。我尝试过使用SELECT DISTINCT u.name并使用GROUP BY u.name,但无法正常使用。

SELECT TOP (100) c.id, u.id u.name, b.sector, u.default
FROM cads AS c 
INNER JOIN users AS u ON c.cad = u.id 
INNER JOIN business AS b ON u.id = b.cad
WHERE (c.[public] = 'True') AND (c.valid = 'True') 
        AND (u.default = '$curr') 
        AND (c.expires IS NULL OR c.expires >= GETDATE()) 
ORDER BY NEWID() 

非常感谢

2 个答案:

答案 0 :(得分:0)

您可以通过狡猾地使用ROW_NUMBER()

来实现
;With Arbitrary AS (
SELECT c.id, u.id u.name, b.sector, u.default,
    ROW_NUMBER() OVER (PARTITION BY u.name ORDER BY newid()) as rn
FROM cads AS c 
INNER JOIN users AS u ON c.cad = u.id 
INNER JOIN business AS b ON u.id = b.cad
WHERE (c.[public] = 'True') AND (c.valid = 'True') 
        AND (u.default = '$curr') 
        AND (c.expires IS NULL OR c.expires >= GETDATE()) 
)
select top 100 * from Arbitrary ORDER BY newid()

(您确实需要两个ORDER BY子句,因为无法保证CTE中的内部实际上会影响TOP运算符正在考虑的行的顺序)

答案 1 :(得分:0)

也许

SELECT TOP (100) min(c.id), u.id, u.name, min(b.sector), min(u.default)
FROM cads AS c 
INNER JOIN users AS u ON c.cad = u.id 
INNER JOIN business AS b ON u.id = b.cad
WHERE (c.[public] = 'True') AND (c.valid = 'True') 
        AND (u.default = '$curr') 
        AND (c.expires IS NULL OR c.expires >= GETDATE())
GROUP BY u.id, u.name 
ORDER BY NEWID()