gpt4 book ai didi

mysql - 将多列 WRT 转置为 MySQL 中的一行

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

我已经搜索过转置和枢轴,但找不到类似的东西。输入表:

+-----+-------+-------+-------+
| TID | TP1 | TP2 | TP3 |
+-----+-------+-------+-------+
| A | link1 | link1 | link3 |
| B | link3 | | |
| C | link2 | | |
+-----+-------+-------+-------+

所需的输出表:

+-----+--------+-------+
| TID | TP Num | REF |
+-----+--------+-------+
| A | 1 | link1 |
| A | 2 | link1 |
| A | 3 | link3 |
| B | 1 | link3 |
| C | 1 | link2 |
+-----+--------+-------+

最佳答案

这有点复杂,您需要使用 union all 来获得垂直表示,然后使用用户定义的变量来获取 nums 的东西

select TID,`TP Num`,REF from (
select TID,REF,@rn:= if (@prev_tid = TID,@rn+1,1) as `TP Num`,@prev_tid:=TID from
(
select
TID,REF from
(
select TID , TP1 as REF from mytable where TP1 is not null and TP1 <> ''
union all
select TID , TP2 as REF from mytable where TP2 is not null and TP2 <> ''
union all
select TID , TP3 as REF from mytable where TP3 is not null and TP3 <> ''
)x
)y,(select @rn:=0,@prev_tid:=null)z
order by TID,REF
)x;

http://sqlfiddle.com/#!9/1d15c/14

关于mysql - 将多列 WRT 转置为 MySQL 中的一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34542112/

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