gpt4 book ai didi

mysql - 如何查询: agregate group by column A for each column B value

转载 作者:行者123 更新时间:2023-11-29 10:59:10 25 4
gpt4 key购买 nike

此时我有以下行值:

Reg table

使用以下内容构建此表:

CREATE TABLE `registros` (
`id_registro` int(11) NOT NULL,
`id_partida` int(11) NOT NULL,
`id_juego` int(11) NOT NULL,
`id_jugador` int(11) NOT NULL,
`score` float NOT NULL DEFAULT '0',
`fecha_creacion` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

INSERT INTO `registros` (`id_registro`, `id_partida`, `id_juego`, `id_jugador`, `score`, `fecha_creacion`) VALUES
(1, 2, 2, 1, 300, '2017-02-27 22:14:50'),
(2, 2, 2, 2, 350, '2017-02-27 22:14:50'),
(3, 2, 2, 3, 365, '2017-02-27 22:14:50'),
(4, 2, 2, 4, 110, '2017-02-27 22:14:50'),
(5, 2, 2, 5, 90, '2017-02-27 22:14:50'),
(6, 2, 2, 6, 840, '2017-02-27 22:15:11'),
(7, 2, 2, 7, 500, '2017-02-27 22:15:11'),
(8, 2, 2, 1, 20, '2017-02-27 22:15:45'),
(9, 2, 2, 1, 610, '2017-02-27 22:15:45'),
(10, 2, 2, 2, 415, '2017-02-27 22:16:07'),
(11, 2, 2, 4, 220, '2017-02-27 22:16:07'),
(13, 3, 1, 1, -600, '2017-02-27 22:17:47'),
(14, 3, 1, 1, -550, '2017-02-27 22:17:47'),
(15, 3, 1, 2, -480, '2017-02-27 22:17:47'),
(16, 3, 1, 2, -700, '2017-02-27 22:17:47'),
(17, 3, 1, 9, -490, '2017-02-27 22:18:18'),
(21, 3, 1, 2, -700, '2017-02-27 22:18:18');

我需要为每个id_partida(游戏比赛)找到一个由id_jugador及其最好成绩(多次参加游戏且得分不同的玩家)组成的组)。

我对每场比赛都有一个“排名”。这是我的 sql 代码:

SELECT registros.id_partida, registros.id_jugador,MAX(registros.score) as best_score
FROM registros
WHERE registros.id_partida = 2
GROUP BY registros.id_jugador
ORDER BY best_score DESC;

执行结果:

id_partida ranking

但我想知道所有比赛的所有排名以及比赛的位置。不仅仅使用带有特定目标id_partida = 2的where子句。如下:

enter image description here

这里是Mysql数据库:http://pastebin.com/8eYuYzgV

谢谢大家。

最佳答案

您可以按两列进行分组:

SELECT registros.id_partida, registros.id_jugador,MAX(registros.score) as best_score
FROM registros
GROUP BY registros.id_jugador, registros.id_partida
ORDER BY best_score DESC;

如果你想在查询中获得排名,那么 MySQL 的查询看起来会稍微复杂一些:

select id_partida, id_jugador, best_score, rank
FROM (
select *,
case when @p=a.id_partida THEN @o:=@o+1 ELSE @o:=1 END as rank,
@p:=a.id_partida
from (
SELECT registros.id_partida, registros.id_jugador,MAX(registros.score) as best_score
FROM registros
GROUP BY registros.id_jugador, registros.id_partida
ORDER BY registros.id_partida, best_score DESC
) a, (select @p:=0, @o:=1) s
) scores

结果:

| id_partida | id_jugador | best_score | rank |
|------------|------------|------------|------|
| 2 | 6 | 840 | 1 |
| 2 | 1 | 610 | 2 |
| 2 | 7 | 500 | 3 |
| 2 | 2 | 415 | 4 |
| 2 | 3 | 365 | 5 |
| 2 | 4 | 220 | 6 |
| 2 | 5 | 90 | 7 |
| 3 | 2 | -480 | 1 |
| 3 | 9 | -490 | 2 |
| 3 | 1 | -550 | 3 |

SQL Fiddle

关于mysql - 如何查询: agregate group by column A for each column B value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42544442/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com