2009-01-19 88 views
0

今天我一直在努力处理这一个SQL查询需求,我想知道是否有人可以帮助我。如何选择一列中唯一的一组随机记录?

我有一个运动问题表。其中一列是与问题相关的团队。我的要求是在团队独特的情况下返回一系列随机问题。

因此,可以说,我们有如下表,并希望5个问题:

Question  Answer  Team 
----------------------------------- 
question 1  answer 1  team A 
question 2  answer 2  team B 
question 3  answer 3  team B 
question 4  answer 3  team D 
question 5  answer 3  team A 
question 6  answer 3  team C 
question 7  answer 3  team F 
question 8  answer 3  team C 
question 9  answer 3  team G 
question 10  answer 3  team D 

有效的结果将返回:

question 1  answer 1  team A 
question 2  answer 2  team B 
question 4  answer 3  team D 
question 6  answer 3  team C 
question 7  answer 3  team F 

我觉得这应该有可能做到这一点作为清洁SQL语句有一些聪明的使用Distinct和Take但我还没有能够把它正确的。

到目前为止最好的解决方案是从Mladen Prajdic。我刚刚稍微更新了一下,以提高它的随机性:

SELECT TOP 10 * 
FROM (SELECT ROW_NUMBER() OVER(PARTITION BY Team ORDER BY Team, NEWID()) AS RN, * 
    FROM Question 
    ) teams 
WHERE RN = 2 
ORDER BY NEWID() 

回答

2

为SQL 2005,你可以这样做:

select top 5 * 
from (
      select ROW_NUMBER() over(partition by team order by team) as RN, * 
      from @t 
     ) t 
where RN = 1 
order by NEWID() 
+0

thanks..have以前从未使用PARTITION关键字。学到了新东西。我稍微更新了查询以改善随机性。 – 2009-01-19 23:02:58

1

这应该做你需要的,在oracle中;对于不同的数据库,显然你需要使用它们的随机数字源。可能有更好的方法;让希望别人会指出来给我们:对

select question, answer, team 
from 
(
select question, answer, team, r 
from 
(
select 
    question, 
    answer, 
    team, 
    rank() over (partition by team order by dbms_random.value) r 
from questions 
) 
where r = 1 
order by dbms_random.value 
) where rownum<=5; 

测试代码:

create table questions(question varchar2(16), answer varchar2(16), team varchar2(16)); 

insert into questions(question, answer, team) 
values ('question 1',  'answer 1',  'team A'); 

insert into questions(question, answer, team) 
values ('question 2',  'answer 2',  'team B'); 

insert into questions(question, answer, team) 
values ('question 3',  'answer 3',  'team B'); 

insert into questions(question, answer, team) 
values ('question 4',  'answer 3',  'team D'); 

insert into questions(question, answer, team) 
values ('question 5',  'answer 3',  'team A'); 

insert into questions(question, answer, team) 
values ('question 6',  'answer 3',  'team C'); 

insert into questions(question, answer, team) 
values ('question 7',  'answer 3',  'team F'); 

insert into questions(question, answer, team) 
values ('question 8',  'answer 3',  'team C'); 

insert into questions(question, answer, team) 
values ('question 9',  'answer 3',  'team G'); 

insert into questions(question, answer, team) 
values ('question 10', 'answer 3',  'team D'); 

commit; 
0

在PostgreSQL(其中有不同),我可能会这样做:

select distinct on (Team) Question, Answer, Team from test order by Team, random() limit 5; 

只是测试它。似乎工作。