简体   繁体   中英

SQL SERVER - select distinct random number of rows

I have the below query that selects 100 random rows. However I also need to select the distinct name. I have tried using SELECT DISTINCT u.name and also using GROUP BY u.name but cannot get anything to work.

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() 

Many thanks

You can do it via cunning use of 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()

(You do need both ORDER BY clauses because there's no guarantee that the inner one in the CTE will actually affect the order of rows being considered by the TOP operator)

Maybe

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() 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM