2016-03-03 43 views
0
| id | user | team | month | result | 
|----|-------|--------|-------|--------| 
| 1 | Joe | red | sept | 100 | 
| 2 | Joe | red | oct | 40  | 
| 3 | Jim | red | sept | 70  | 
| 4 | Jim | red | oct | 50  | 
| 5 | Susy | red | sept | 40  | 
| 6 | Tim | blue | sept | 60  | 
| 7 | Tim | blue | oct | 100 | 
| 8 | Betty | blue | sept | 70  | 
| 9 | Dave | blue | sept | 20  | 
| 10 | Stan | green | oct | 40  | 
| 11 | Alan | green | sept | 80  | 
| 12 | Tina | green | oct | 100 | 
| 13 | Tina | green | sept | 30  | 
| 14 | Rick | yellow | oct | 50  | 
| 15 | Ellen | yellow | oct | 60  | 

這是可能的。每個團隊最多可以有2名用戶獲得最大成績MYSQL

我需要爲每個團隊最多2位用戶提供最大的結果。

如下面的結果是從每隊2名球員得分最高:

| 1 | Joe | red | sept | 100 | 
| 3 | Jim | red | sept | 70  | 
| 7 | Tim | blue | oct | 100 | 
| 8 | Betty | blue | sept | 70  | 
| 12 | Tina | green | oct | 100 | 
| 11 | Alan | green | sept | 80  | 
| 15 | Ellen | yellow | oct | 60  | 
| 14 | Rick | yellow | oct | 50  | 

,或者被多次查詢做到這一點的唯一途徑?

+0

'達2'?你的意思是因爲一支球隊可能只有一個結果? – Strawberry

+0

是的,一個團隊可能只有一個成員 – John

回答

2

你可以嘗試以下方法:

select t.* 
from `tbl` t 
where (select count(*) 
     from `tbl` 
     where `team` = t.`team` and `result` >= t.`result`) < 3 

SQLFiddle

3

你可以這樣說:

SELECT * FROM 
    (SELECT t.id,t.team,count(*) as rnk 
    FROM YourTable t 
    INNER JOIN YourTable s 
    ON(t.id = s.id and t.team = s.team and t.result >= s.result))x 
WHERE rnk <= 2 
+1

感謝編輯@Mihai – Yossi

相關問題