gpt4 book ai didi

mysql - 仅从 1 行中选择并订购

转载 作者:行者123 更新时间:2023-11-29 16:14:24 27 4
gpt4 key购买 nike

我的数据库中有一个大约有 50 列的表。现在我想编写一个 Select 来订购 1 行中的日期。

示例表:

ID | foo1   |  f1_rank |  foo2    |  f2_rank | foo3    | f3_rank
----------------------------------------------------------------
1 | bar1 | 3 | bar2 | 1 | bar3 | 2
2 | babar1 | 1 | barbar2 | 3 | barbar3 | 2

选择应根据“f*_rank”对 foo1、foo2 和 foo3 列进行排序,像这样:

For ID1:
bar2
bar3
bar1

对于 ID2:barbar1、barbar3、barbar2

我不知道如何达到这个目标。交错一些选择语句的正确方法是吗?

感谢您的帮助!

最佳答案

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)

对于五十列来说,这会有点无聊。

关于mysql - 仅从 1 行中选择并订购,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54959571/

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