我有这张桌子:
id game points player
---|-----|-------|--------
1 | 1 | 6 | John
2 | 1 | 5 | Adam
3 | 1 | 7 | Brian
4 | 1 | 8 | Alan
5 | 2 | 6 | John
6 | 2 | 2 | Adam
7 | 2 | 4 | Brian
8 | 2 | 3 | Alan
我正在尝试编写一个查询,计算一个人赢了多少金牌,银牌和铜牌。
Alan的结果应该是:([gold] = 1,[silver] = 0,[bronze] = 1)
Brian应该是:( [gold] = 0,[silver] = 2,[bronze] = 0)
我能够像这样计算金牌:
SELECT COUNT(*) AS gold
FROM (`myTable` AS t)
WHERE `t`.`player` = 'Alan'
AND `t`.points = (
SELECT MAX(`points`)
FROM `myTable` as tsub
WHERE `tsub`.`game` = `t`.`game`
)
银牌和铜牌似乎要困难得多。
有人有什么想法吗?
由于
编辑: 澄清如何颁发奖章。
黄金:转到游戏中得分最高的玩家。
Silver:进入游戏中得分第二高的玩家。
青铜:进入游戏中得分第三高的玩家。
Multple游戏存储在表格中。
如果两名球员获得金牌,则不会颁发银牌。 两个最高分是平局,所以下一个最高分将是第三高分,因此将获得铜牌。
答案 0 :(得分:0)
这将有所帮助
如果需要,请更新您的奖牌标准
select
name,
(SELECT count(*) FROM myTable g where g.points > 5 and g.name=myTable.name) as gold,
(SELECT count(*) FROM myTable g where g.points > 2 and g.points <= 5 and g.name=myTable.name) as silver,
(SELECT count(*) FROM myTable g where g.points <= 2 and g.name=myTable.name) as gold
from myTable
group by name
答案 1 :(得分:0)
考虑这个例子......
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(game INT NOT NULL
,points INT NOT NULL
,player VARCHAR(12) NOT NULL
,PRIMARY KEY(game,player)
);
INSERT INTO my_table VALUES
(1,6,'John'),
(1,5,'Adam'),
(1,7,'Brian'),
(1,8,'Alan'),
(2,6,'John'),
(2,2,'Adam'),
(2,4,'Brian'),
(2,3,'Alan');
SELECT player
, SUM(rank=1) gold
, SUM(rank=2) silver
, SUM(rank=3) bronze
FROM
(
SELECT x.*
, COUNT(*) rank
FROM my_table x
JOIN my_table y
ON y.game = x.game
AND y.points >= x.points
GROUP
BY game
, player
) a
GROUP
BY player;
+--------+------+--------+--------+
| player | gold | silver | bronze |
+--------+------+--------+--------+
| Adam | 0 | 0 | 0 |
| Alan | 1 | 0 | 1 |
| Brian | 0 | 2 | 0 |
| John | 1 | 0 | 1 |
+--------+------+--------+--------+