在sql server中的列到行?

2022-01-22 00:00:00 pivot sql tsql sql-server-2008 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

解决方案

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;

相关文章