SQL-在MySQL中将一列分为两列

时间:2018-10-11 18:13:53

标签: mysql sql

我有这张桌子。考虑到id从0开始。

表1

ID     Letter
1        A
2        B
3        C
4        D
6        E

我需要以下输出

Col1     Col2
NULL      A
B         C
D         NULL
E         NULL

我尝试使用id为id-1和id +1的并集,但我不知道如何根据id获取字母,甚至尝试了奇数逻辑但无济于事。

感谢您的帮助。

谢谢

2 个答案:

答案 0 :(得分:3)

您没有发布数据库引擎,所以我假设P​​ostgreSQL的模数操作数为%

查询应为:

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)

请选择以下选项,因为我没有在MySQL 5.6中对其进行测试的方法。在没有完整的外部联接的情况下,可以执行两个外部联接,然后可以将它们合并,如下所示:

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

答案 1 :(得分:3)

只需使用条件聚合:

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);

如果愿意,可以使用mod()代替%。 MySQL两者都支持。