选择一列,拆分为多列

时间:2018-08-24 15:57:50

标签: sql oracle

我在Oracle数据库中有一个如下表:

res_code  column1  ...
-------------------------------
001       A
002       B
003       C
004       D
005       E

我想从此表中进行选择以得到如下结果:

res_code1  res_code2
-------------------------------
001       002
003       004
005       ...

提示:res_code1和res_code2都属于res_code,不能重复。 可以使用sql吗?

3 个答案:

答案 0 :(得分:2)

您可以使用SQL这样简单地完成此操作:

with odds as
(
select res_code, cast(res_code as int) as rn 
from myTable 
where mod(cast(res_code as int) ,2) =1
),
evens as 
(
select res_code, cast(res_code as int) as rn 
from myTable 
where mod(cast(res_code as int) ,2) =0
)
select odds.res_code as res_code1, evens.res_code as res_code2 
from odds
left join evens on evens.rn = odds.rn+1;

答案 1 :(得分:2)

您可以尝试此操作,使用row_number制作rn,然后执行MOD拆分组。

在主查询中做一些算术运算。

CREATE TABLE T(
   res_code VARCHAR(50),
   column1 VARCHAR(50)
);


INSERT INTO T VALUES ('001' ,'A');
INSERT INTO T VALUES ('002' ,'B');
INSERT INTO T VALUES ('003' ,'C');
INSERT INTO T VALUES ('004' ,'D');
INSERT INTO T VALUES ('005' ,'E');

查询1

with cte as (
  select t1.*, 
         MOD(row_number() over (order by column1) ,2) rn,
         ceil(row_number() over (order by column1) / 2) grp1
  from T t1
)
select MAX(CASE WHEN rn = 1 THEN t1.RES_CODE END) res_code1,
       MAX(CASE WHEN rn = 0 THEN t1.RES_CODE END) res_code2
from cte t1
group by grp1

Results

| RES_CODE1 | RES_CODE2 |
|-----------|-----------|
|       001 |       002 |
|       003 |       004 |
|       005 |    (null) |

答案 2 :(得分:1)

使用光标进行两次提取和单次插入:

declare @res_code1 nvarchar(100), @res_code2 nvarchar(100), @even int

declare @newtable table(res_code1 nvarchar(100), res_code2 nvarchar(100))

declare cur cursor for (select res_code from @mytable)
open cur

-- assume first 2 rows are available
fetch next from cur into @res_code1
fetch next from cur into @res_code2
-- set @even to 1 meaning even value has been fetched
set @even = 1

while @@FETCH_STATUS = 0
begin
  if @even = 0
  begin
    -- fetch @res_code2
    fetch next from cur into @res_code2
    set @even = 1
  end
  else
  begin
    -- insert into table since @even = 1 (has even number)
    insert into @newtable values(@res_code1,@res_code2)
    -- fetch @res_code1
    fetch next from cur into @res_code1
    set @even = 0
  end
end

-- insert the last odd
if @even = 1
  insert into @newtable values(@res_code1,'')