我的数据库中有一个表,其中包含大约50个cols。现在我想写一个Select to order date from 1 row。
示例表:
ID | foo1 | f1_rank | foo2 | f2_rank | foo3 | f3_rank
----------------------------------------------------------------
1 | bar1 | 3 | bar2 | 1 | bar3 | 2
2 | babar1 | 1 | barbar2 | 3 | barbar3 | 2select应根据"f*_rank“对foo1、foo2和foo3 cols进行排序,如下所示:
For ID1:
bar2
bar3
bar1对于ID2: barbar1、barbar3、barbar2
我不知道怎样才能达到这个目的。交错一些select语句是正确的方式吗?
谢谢你的帮忙!
发布于 2019-03-02 23:14:18
Mysql不能按行排序,但您可以先取消透视,然后再透视/条件聚合
select id,
max(case when rnk = 1 then foo else null end) foo1,
max(case when rnk = 2 then foo else null end) foo2,
max(case when rnk = 3 then foo else null end) foo3
from
(
select id, foo1 foo,f1_rank rnk from t
union all
select id, foo2,f2_rank from t
union all
select id, foo3,f3_rank from t
) s
group by id;
+------+--------+---------+---------+
| id | foo1 | foo2 | foo3 |
+------+--------+---------+---------+
| 1 | bar2 | bar3 | bar1 |
| 2 | babar1 | barbar3 | barbar2 |
+------+--------+---------+---------+
2 rows in set (0.00 sec)对于50列,这将是一个有点无聊。
https://stackoverflow.com/questions/54959571
复制相似问题