开发者

Random select preventing some duplicates

开发者 https://www.devze.com 2023-02-13 12:27 出处:网络
From Table Name GroupID aNull b1 c1 d2 eNull fNull g3 Result expected from random top 4 selection Name GruopID

From Table

Name GroupID 
a      Null
b       1
c       1
d       2
e      Null
f      Null
g       3

Result expected from random top 4 selection

Name GruopID
a  Null
b   1
e  Null
g   3

Resuming I want to get random names but only 1 kind of groupid if groupid is <> null The select Newid() type returns "Select Top(4) * FROM Table Order By NEWID()"

Name GruopID
a  Null
b   1
e  Null
c   1

I don´t want that. Hope i made my self clear开发者_StackOverflow! Thanks in advance


You can try this (on SQL Server 2005+).

;WITH CTE AS
(
    SELECT *, ROW_NUMBER() OVER(PARTITION BY GroupId ORDER BY NEWID()) Corr
    FROM YourTable
)

SELECT TOP 4 Name, GroupId
FROM CTE
WHERE GroupId IS NULL OR Corr = 1
ORDER BY NEWID()
0

精彩评论

暂无评论...
验证码 换一张
取 消