Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

column to row in sql server?

Table:

CREATE TABLE Table1 (
  col1 INT, 
  col2 nvarchar(10), 
  col3 INT, 
  col4 INT
);

INSERT INTO Table1 
  (col1, col2, col3, col4) 
VALUES 
  (1, 'welcome', 3, 4);

My table have different data type , col2 is nvarchar h can i do this ...

result:

col    value
---------------
col1   1
col2   welcome
col3   3
col4   4
like image 540
jay Avatar asked Oct 18 '10 02:10

jay


People also ask

How can I change column to row in SQL Server?

In order to reverse a PIVOT operator, that is, to convert data from column-level back to row-level and get the original table, you can use the UNPIVOT operator.

Can we transpose data in SQL?

A transposition is to rotate information from one row or column to another to change the data layout, for the purpose of making observations from a new perspective. Some transposition algorithms are simple, such as row to column, column to row and bidirectional transposition.


2 Answers

You can use the UNPIVOT operation to get your results

SELECT col, value
FROM 
   (SELECT CAST(col1 AS VARCHAR) AS col1, CAST(col2 AS VARCHAR) AS col2,
        CAST(col3 AS VARCHAR) AS col3, CAST(col4 AS VARCHAR) AS col4
   FROM Table1) p
UNPIVOT
   (value FOR col IN 
      (col1, col2, col3, col4)
) AS unpvt;
like image 148
bobs Avatar answered Oct 05 '22 02:10

bobs


Use:

SELECT 'col1' AS col,
        CAST(t1.col1 AS NVARCHAR(10)) AS value
   FROM TABLE_1 t1
UNION ALL
SELECT 'col2' AS col,
        t2.col2 AS value
   FROM TABLE_1 t2
UNION ALL
SELECT 'col3' AS col,
       CAST(t3.col3 AS NVARCHAR(10)) AS value
  FROM TABLE_1 t3
UNION ALL
SELECT 'col4' AS col,
       CAST(t4.col4 AS NVARCHAR(10)) AS value
  FROM TABLE_1 t4

Part of the problem is that you need to make the second column the same data type:

  • CAST/CONVERT
like image 30
OMG Ponies Avatar answered Oct 05 '22 01:10

OMG Ponies