0

I have a table test looks like

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

My goal is to get a table test 2 like

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

Is it possible within SQL Server?

3
  • 4
    You can't have the same column name twice. How are we supposed to chose one of the two CA's? Commented Jul 7, 2015 at 8:12
  • You can create view as per your table Commented Jul 7, 2015 at 8:13
  • 1
    I dont think you have a table like you showed us.. Commented Jul 7, 2015 at 8:13

3 Answers 3

2

Try this,

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) 
Sign up to request clarification or add additional context in comments.

1 Comment

why use both CROSS APPLY and UNION ALL in the same query?
2

Change columns names, then do a UNION ALL:

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

Comments

0

CATTC column is dublicate, change to CATTC_ and use "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 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.