[英]SQL - Split a column into two columns in Mysql
I have this table. 我有这张桌子。 Considering the id starts from 0.
考虑到id从0开始。
Table 1 表格1
ID Letter 1 A 2 B 3 C 4 D 6 E
I need following output 我需要以下输出
Col1 Col2 NULL A B C D NULL E NULL
I tried using union with id, id - 1 and id + 1, but I couldn't figure out how to get letter based on ids, also tried even odd logic but nothing worked. 我尝试使用带有id,id - 1和id + 1的union,但是我无法弄清楚如何根据id获取字母,也尝试了奇怪的逻辑但没有任何效果。
Any help is appreciated. 任何帮助表示赞赏。
Thank you 谢谢
You didn't post the database engine, so I'll assume PostgreSQL where the modulus operand is %
. 你没有发布数据库引擎,所以我假设模数操作数为
%
PostgreSQL。
The query should be: 查询应该是:
select o.letter, e.letter
from (
select id, letter, id as base from my_table where id % 2 = 0
) o full outer join (
select id, letter, (id - 1) as base from my_table where id % 2 <> 0
) e on e.base = o.base
order by coalesce(o.base, e.base)
Please take the following option with a grain of salt since I don't have a way of testing it in MySQL 5.6. 请使用以下选项,因为我没有在MySQL 5.6中测试它的方法。 In the absence of a full outer join, you can perform two outer joins, and then you can union them, as in:
如果没有完整的外部联接,您可以执行两个外部联接,然后可以将它们联合起来,如下所示:
select * from (
select o.base, o.letter, e.letter
from (
select id, letter, id as base from my_table where id % 2 = 0
) o left join (
select id, letter, (id - 1) as base from my_table where id % 2 <> 0
) e on e.base = o.base
union
select e.base, o.letter, e.letter
from (
select id, letter, id as base from my_table where id % 2 = 0
) o right join (
select id, letter, (id - 1) as base from my_table where id % 2 <> 0
) e on e.base = o.base
) x
order by base
Just use conditional aggregation: 只需使用条件聚合:
select max(case when id % 2 = 0 then letter end) as col1,
max(case when id % 2 = 1 then letter end) as col2
from t
group by floor(id / 2);
If you prefer, you can use mod()
instead of %
. 如果您愿意,可以使用
mod()
而不是%
。 MySQL supports both. MySQL支持两者。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.