mysql - 通过 SQL 查询重新配置行中的表列数据

标签 mysql sql pivot

如果其他人回答了这个问题,请原谅我;我有一个工作表,我试图通过查询在 MySQL 中重新排列。工作表如下所示:

+-------+------+-------+
| Sport |Points| Name  |
+-------+------+-------+
| A     |   53 | Alex  |
| A     |   22 | Jim   |
| A     |   11 | Josh  |
| B     |   63 | Joe   |
| B     |   22 | Rich  |
| B     |   10 | Frank |
+-------+------+-------+

我正在寻找一种通过 sql 查询以这种格式输出表的有效方法:

+-------+-----+---------+-----+---------+-----+---------+
| Sport | 1st | 1stName | 2nd | 2ndName | 3rd | 3rdName |
+-------+-----+---------+-----+---------+-----+---------+
| A     |  53 | Alex    |  22 | Jim     |  11 | Josh    |
| B     |  63 | Joe     |  22 | Rich    |  10 | Frank   |
+-------+-----+---------+-----+---------+-----+---------+

通常我不会以这种方式格式化我的表格,但它让我更容易通过 PHP 显示每项运动的前 3 名球员。绝对欢迎任何有效的建议。谢谢!

最佳答案

首先使用基于每项运动得分降序排列的变量计算行数。

select sport,points,name,
,@rn:=case when sport=@prev_sport then @rn+1 else @rn end
,@prev_sport:=sport
from t
join (select @rn:=1,@prev_sport:='')
order by sport,points desc

然后使用条件聚合获取一行中每项运动的前 3 名得分。

select sport
,max(case when rnum=1 then points end) as p_1
,max(case when rnum=1 then name end) as n_1
,max(case when rnum=2 then points end) as p_2
,max(case when rnum=2 then name end) as n_2
,max(case when rnum=3 then points end) as p_3
,max(case when rnum=3 then name end) as n_3
from (
select sport,points,name
,@rn:=case when sport=@prev_sport then @rn+1 else 1 end as rnum
,@prev_sport:=sport
from t
join (select @rn:=1,@prev_sport:='') r
order by sport,points desc
) x
group by sport

如果积分相同,则任意选取一个名字。

要打破联系以显示最低或最高的名称,可以轻松更改上述查询以包含名称排序。

select sport
,max(case when rnum=1 then points end) as p_1
,max(case when rnum=1 then name end) as n_1
,max(case when rnum=2 then points end) as p_2
,max(case when rnum=2 then name end) as n_2
,max(case when rnum=3 then points end) as p_3
,max(case when rnum=3 then name end) as n_3
from (
select sport,points,name
,@rn:=case when sport=@prev_sport then @rn+1 else 1 end as rnum
,@prev_sport:=sport
from t
join (select @rn:=1,@prev_sport:='') r
order by sport,points desc,name --change it to name desc if the highest name should be shown in case of ties
) x
group by sport

关于mysql - 通过 SQL 查询重新配置行中的表列数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42939936/

相关文章:

mysql - 解决复杂的 SQL 删除查询问题

php - MYSQL insert or update if exists on one-way composite primary key table 单向复合主键表

MySQL DELETE 查询性能调优

mysql - 以某种语言获取行的 SQL 查询(使用默认语言)

sql - SQL Server 中的嵌套 SQL 事务

将长数据 reshape 为多个宽列

Excel:数据透视表不过滤

mysql更新并设置当前行最后8小时的总和值

php - 如何在 PostgreSQL 中将空值转换为空值?

sql - 如何在 SQL Server 中每月 31 天按天循环执行 PIVOT