SQLselect随机记录

SQL select random record

我有一个如下所示的 table,并希望 select 不同的人,例如第 2、9、11、20 行。我不想 select MAX() 作为那不是随机的。而且我不想 select Jack 两次。每组记录需要一个人

ID  Name    Category Level
1   Jack    Dragon     3
2   Jack    Falls      5
3   Jack    Spider     5
4   Jack    Apprentice 1
5   Jack    Jolly      5
6   Luke    Dragon     1
7   Luke    Falls      1
8   Luke    Spider     3
9   Luke    Apprentice 5
10  Luke    Jolly      5
11  Mark    Dragon     3
12  Mark    Falls      3
13  Mark    Spider     1
14  Mark    Apprentice 3
15  Mark    Jolly      1
16  Sam     Dragon     3
17  Sam     Falls      5
18  Sam     Spider     5
19  Sam    Apprentice  5
20  Sam    Jolly       3
SELECT DISTINCT name
from tbl
ORDER BY NEWID()

这似乎比听起来更棘手,创建一个带有额外 tempId 列的 temp table 应该可行。尝试:

create table #temp(ID int, Name char(10), Category char(10), Level int, tempId varchar(36))

insert #temp select ID, Name, Category, Level, NEWID() as 'tempId' from yourTable
select ID, Name, Category, Level from #temp where ID IN
    (select min(tempId) from #temp group by Name)

drop table #temp

假设记录集 = 具有相同值 "Name" 的行:

with cte_random
as
(
select *, rank() over (partition by forenames order by newid()) as rnk from tbl
)
select id, name, category, level from cte_random where rnk = 1