2009-01-19 151 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; 

只是測試它。似乎工作。