我的问题肯定是平庸的,但我无法设置一个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查询? 提前感谢您的回答。
马修
答案 0 :(得分:2)
没有位置栏,这很容易。只需执行以下操作
SELECT Country,COUNT(*) AS medals
FROM MyTable
GROUP BY Country
ORDER BY COUNT(*) DESC
LIMIT 3;
有一些更复杂的代码用于获取“位置”列,但除非您需要它,否则可能没有必要,您可以使用处理代码上的计数器获取这些数字。如果你有兴趣,代码就是这样的。
SELECT @rownum:=@rownum+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 :(得分: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)。
答案 2 :(得分:0)
没有排名会更简单,如果你可以在程序的逻辑中添加它:
SELECT `country`, COUNT(*) total
FROM medal
GROUP BY country
ORDER BY total DESC
LIMIT 3
看起来Kibbee也打败了我,但对于保证GROUP BY
兼容的查询,你可以将上面的内容包装在自己的SELECT
中:
SELECT @n:=@n+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