2011-10-31 91 views
0

我的問題肯定是平庸的,但我無法建立一個sql查詢,它允許我製作一個體育事件總結表的前3個國家的列表。 我更好地解釋我:在一項體育賽事中,我有很多來自不同國家的運動員,我需要製作一張彙總表,顯示贏得更多獎牌的國家。 下面是一個例子:排名前三的國家

-------------------------------------------- 
|id |  name | activity | country | 
-------------------------------------------- 
| 1 | John  | 100m  | USA  | 
| 2 | Andy  | 200m  | CANADA | 
| 3 | Frank  | 400m  | USA  | 
| 4 | Ian  | 400m  | GERMANY | 
| 5 | Anthony | 100m  | USA  | 
| 6 | Eric  | 400m  | CANADA | 
| 7 | Mike  | 200m  | UK  | 
| 8 | Dave  | 200m  | GERMANY | 
| 9 | Richard | 100m  | USA  | 
| 10| Max  | 100m  | USA  | 
| 11| Randy  | 100m  | USA  | 
| 12| Maurice | 400m  | CANADA | 
| 13| Col  | 100m  | UK  | 
| 14| Jim  | 400m  | USA  | 
| 15| Adam  | 200m  | BRAZIL | 
| 16| Ricky  | 100m  | UK  | 
| 17| Emily  | 400m  | USA  | 
| 18| Serge  | 200m  | UK  | 
| 19| Alex  | 400m  | FRANCE | 
| 20| Enamuel | 100m  | USA  | 
-------------------------------------------- 

彙總表我希望得到如下:

前3個國家

-------------------------------------- 
| position | country | medals | 
-------------------------------------- 
|  1 |  USA  | 9 | 
|  2 |  UK  | 4 | 
|  3 |  CANADA | 3 | 
-------------------------------------- 

如何建立QSL查詢? 在此先感謝您的答覆。

Mattew

回答

2

沒有位置列,這很容易。只要做到以下

SELECT Country,COUNT(*) AS medals 
FROM MyTable 
GROUP BY Country 
ORDER BY COUNT(*) DESC 
LIMIT 3; 

沒有爲獲得「位置」列了一些更復雜的代碼,但除非你需要它,它可能是沒有必要的,而且您也可以利用計數器只得到這些數字處理代碼。如果你有興趣,代碼會是這樣的。

SELECT @rownum:[email protected]+1 AS Position,Country,Medals FROM 
(
SELECT Country,COUNT(*) AS medals 
FROM Medals 
GROUP BY Country 
ORDER BY COUNT(*) DESC 
LIMIT 3 
) AS Stats, (SELECT @rownum:=0) RowNum; 

上述查詢已經過測試,似乎按照您的需要正常工作。

+1

是的,沒有位置列,這很容易... – Thilo

+1

他問如何從結果中產生另一個(摘要)表。小菜一碟 - 將SQL插入到帶有自動增加字段(位置)的新表中, –

0

這是沒有軍銜簡單得多,如果你可以添加在您的程序邏輯代替:

SELECT `country`, COUNT(*) total 
FROM medal 
GROUP BY country 
ORDER BY total DESC 
LIMIT 3 

貌似基比打我太多,但爲保證GROUP BY兼容查詢你可以用在上面其自身的SELECT

SELECT @n:[email protected]+1 AS rank, country, total 
FROM 
    (
    SELECT `country`, COUNT(*) total 
    FROM medal 
    GROUP BY country 
    ORDER BY total DESC 
    LIMIT 3 
) t1, 

(SELECT @n:=0) t2 
1
CREATE TABLE IF NOT EXISTS top_three_countries 
    (position INT NOT NULL AUTO_INCREMENT, country VARCHAR(30), medals INT); 
TRUNCATE TABLE top_three_countries; 
INSERT INTO top_three_countries (country, medals) 
    SELECT country, count(*) total 
    FROM medal 
    GROUP BY country 
    ORDER BY total DESC 
    LIMIT 3; 

這將產生一個彙總表(top_three_countries)爲你描述。