mysql: order -> limit -> sum... 可能吗?
mysql: order -> limit -> sum... possible?
我因以下问题而失去它:
我有一个 table 参与者和分数。每个参与者最多可以有 11 个积分条目,我只想要前 6 个的总和。
在这个例子中,假设我们想要 3 个中的前 2 个
+----+---------------+--------+
| id | participantid | points |
+----+---------------+--------+
| 1 | 1 | 11 |
+----+---------------+--------+
| 2 | 3 | 1 |
+----+---------------+--------+
| 3 | 3 | 4 |
+----+---------------+--------+
| 4 | 2 | 3 |
+----+---------------+--------+
| 5 | 1 | 5 |
+----+---------------+--------+
| 6 | 2 | 10 |
+----+---------------+--------+
| 7 | 2 | 9 |
+----+---------------+--------+
| 8 | 1 | 3 |
+----+---------------+--------+
| 9 | 3 | 4 |
+----+---------------+--------+
因此我想要
+---------------+--------+
| participantid | points |
+---------------+--------+
| 2 | 19 |
+---------------+--------+
| 1 | 16 |
+---------------+--------+
| 3 | 8 |
+---------------+--------+
(结果点数降序排列)
mysql 完全可以做到这一点吗?在一个查询中?
哦,生成的参与者 ID 应该从另一个 'partcipant' table 解析为真实姓名,其中
+----+------+
| id | name |
+----+------+
| 1 | what |
+----+------+
| 2 | ev |
+----+------+
| 3 | er |
+----+------+
但在某个时候加入连接应该是可行的...我知道...
使用 ROW_NUMBER() in MySQL 中的答案之一计算行数,然后修改以获得顶部。
SELECT ParticipantId, SUM(Points)
FROM
(
SELECT a.participantid, a.points, a.id, count(*) as row_number
FROM scores a
JOIN scores b ON a.participantid = b.participantid AND cast(concat(a.points,'.', a.id) as decimal) <= cast(concat(b.points,'.', b.id) as decimal)
GROUP BY a.participantid, a.points, a.id
) C
WHERE row_number IN (1,2)
GROUP BY ParticipantId
在我用 id 随意破坏关系之前,我一直有问题
我因以下问题而失去它:
我有一个 table 参与者和分数。每个参与者最多可以有 11 个积分条目,我只想要前 6 个的总和。
在这个例子中,假设我们想要 3 个中的前 2 个
+----+---------------+--------+
| id | participantid | points |
+----+---------------+--------+
| 1 | 1 | 11 |
+----+---------------+--------+
| 2 | 3 | 1 |
+----+---------------+--------+
| 3 | 3 | 4 |
+----+---------------+--------+
| 4 | 2 | 3 |
+----+---------------+--------+
| 5 | 1 | 5 |
+----+---------------+--------+
| 6 | 2 | 10 |
+----+---------------+--------+
| 7 | 2 | 9 |
+----+---------------+--------+
| 8 | 1 | 3 |
+----+---------------+--------+
| 9 | 3 | 4 |
+----+---------------+--------+
因此我想要
+---------------+--------+
| participantid | points |
+---------------+--------+
| 2 | 19 |
+---------------+--------+
| 1 | 16 |
+---------------+--------+
| 3 | 8 |
+---------------+--------+
(结果点数降序排列)
mysql 完全可以做到这一点吗?在一个查询中?
哦,生成的参与者 ID 应该从另一个 'partcipant' table 解析为真实姓名,其中
+----+------+
| id | name |
+----+------+
| 1 | what |
+----+------+
| 2 | ev |
+----+------+
| 3 | er |
+----+------+
但在某个时候加入连接应该是可行的...我知道...
使用 ROW_NUMBER() in MySQL 中的答案之一计算行数,然后修改以获得顶部。
SELECT ParticipantId, SUM(Points)
FROM
(
SELECT a.participantid, a.points, a.id, count(*) as row_number
FROM scores a
JOIN scores b ON a.participantid = b.participantid AND cast(concat(a.points,'.', a.id) as decimal) <= cast(concat(b.points,'.', b.id) as decimal)
GROUP BY a.participantid, a.points, a.id
) C
WHERE row_number IN (1,2)
GROUP BY ParticipantId
在我用 id 随意破坏关系之前,我一直有问题