转换SQL Server中的表

时间:2015-07-07 08:10:48

标签: sql sql-server

我的表测试看起来像

Month|CA     |CATTC | CA     |CATTC
------------------------------------
1    |100    |20    | 250    |120  
5    |100    |30    | 202    |140  
12   |130    |260   | 255    |130 

我的目标是获得一张test 2

Month|CA     |CATTC    
--------------------
1    |100    |20       
5    |100    |30        
12   |130    |260        
1    |250    |120   
5    |202    |140   
12   |255    |130   

是否可以在SQL Server中使用?

3 个答案:

答案 0 :(得分:2)

更改列名称,然后执行UNION ALL

select Month, CA1 as CA, CATTC1  as CATTC from tablename
UNION ALL
select Month, CA2, CATTC2 from tablename

答案 1 :(得分:2)

试试这个,

CREATE TABLE #TEMP
(
    [Month] INT,
    CA INT,
    CASTTC INT,
    CA1 INT,
    CATTC1 INT
)


INSERT INTO #TEMP VALUES
(1    ,100    ,20    , 250    ,120),  
(5    ,100    ,30    , 202    ,140),  
(12   ,130    ,260   , 255    ,130) 

SELECT [Month],CrossApplied.CA,CrossApplied.CASTTC FROM #TEMP
CROSS APPLY (VALUES (CA,CASTTC),(CA1,CATTC1)) CrossApplied(CA,CASTTC)

(OR)

SELECT [Month],
       CrossApplied.CA,
       CrossApplied.CASTTC
FROM   #TEMP
       CROSS APPLY (SELECT CA,
                           CASTTC
                    UNION ALL
                    SELECT CA1,
                           CATTC1) CrossApplied(CA, CASTTC) 

答案 2 :(得分:0)

CATTC专栏是dublicate,改为CATTC_ 并使用" union all"

CREATE TABLE #dt
(
    [Month] INT,
    CA INT,
    CATTC INT,
    CA1 INT,
    CATTC_ INT
)

INSERT INTO #dt VALUES
(1    ,100    ,20    , 250    ,120),  
(5    ,100    ,30    , 202    ,140),  
(12   ,130    ,260   , 255    ,130) 

select [Month], CA, CATTC  from #dt
union all 
select [Month], CA, CATTC_ from #dt