开发者

Random select preventing some duplicates

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜