如何拆分列和行值

时间:2013-04-25 07:30:48

标签: sql sql-server sql-server-2005

使用sql Server 2005

id value1 value2

001 200 300
002 200x300 400x200
003 300x200 500x600
004 100 200
.....

我想将值列拆分为2列

If value1 row 200x300 then it should display value1 - 200 and value2 - 300
if value2 row 400x200 then it should display value1 - 400 and value2 - 200

预期输出

id value1 value2

001 200 300
002 200 300
002 400 200
003 300 200
003 500 600
004 100 200
....

如何做到这一点。

需要SQL查询帮助

3 个答案:

答案 0 :(得分:0)

试试这个

select * from 
(
select * from Table2 where CHARINDEX('x',value1)=0 and CHARINDEX('x',value2)=0
union all
select ID,
CASE WHEN CHARINDEX('x',value1)>0 then LEFT(value1,CHARINDEX('x',value1)-1) END as value1,
CASE WHEN CHARINDEX('x',value1)>0 then RIGHT(value1,CHARINDEX('x',value1)-1) else value2 end as value2
from Table2
where CHARINDEX('x',value1) > 0 
union all
select ID,
CASE WHEN CHARINDEX('x',value2)>0 then LEFT(value2,CHARINDEX('x',value2)-1) END as value1,
CASE WHEN CHARINDEX('x',value2)>0 then RIGHT(value2,CHARINDEX('x',value2)-1) else value2 end as value2
from Table2
where CHARINDEX('x',value2) > 0 
) a
order by 1

答案 1 :(得分:0)

请试试这个..

    --Create Table :
    Create Table #Temp
    (
    Id  Varchar(10),
    Value1  Varchar(10),
    Value2  Varchar(10)
    )

    --Insert Values :
    Insert into #Temp Values ('001','200','300')
    Insert into #Temp Values ('002','200x300','400x200')
    Insert into #Temp Values ('003','300x200','500x600')
    Insert into #Temp Values ('004','100','200')

    --View Data :
    Select * from  #Temp

    --Query  for Exepected OutPut :
    Select Id,Value1,Value2 from #Temp Where (  Value1 not Like '%x%'  and  Value2 not Like '%x%' )
    Union all
    Select  Id,
    SUBSTRING(Value1,1,CharIndex('x',Value1)-1) as Value1,
    SUBSTRING(Value1,CharIndex('x',Value1)+1,Len(Value1)) as Value2
    from #Temp Where ( Value1  Like '%x%'  )
    Union all
    Select Id,
    SUBSTRING(Value2,1,CharIndex('x',Value2)-1) as Value1,
    SUBSTRING(Value2,CharIndex('x',Value2)+1,Len(Value2)) as Value2
    from #Temp Where ( Value2  Like '%x%'  )
    Order by ID

    --Clean Up:
    Drop table #Temp

答案 2 :(得分:0)

请检查:

DECLARE @table as TABLE(id nvarchar(10), Value1 Nvarchar(50), Value2 nvarchar(50))
insert into @table values
('001', '200', '300'),
('002', '200x300', '400x200'),
('003', '300x200', '500x600'),
('004', '100', '200')

select id, Value1, Value2 From @table
select id, Value1, Value2 From @table where CHARINDEX('x', Value2)=0
union all
select id, SUBSTRING(Value1, 1, CHARINDEX('x', Value1)-1) Value1, SUBSTRING(Value1, CHARINDEX('x', Value1)+1, LEN(Value1)) Value2  From @table where CHARINDEX('x', Value2)>0
union all
select id, SUBSTRING(Value2, 1, CHARINDEX('x', Value2)-1) Value1, SUBSTRING(Value2, CHARINDEX('x', Value2)+1, LEN(Value1)) Value2  From @table where CHARINDEX('x', Value2)>0
order by id