column to row in sql server?

2019-02-17 21:47发布

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

3条回答
Bombasti
2楼-- · 2019-02-17 22:01
with rows(n)
as
(
  select 1 
  union all
  select n + 1
  from rows
  where n + 1 <= 4 
 )
   select case n 
          when 1 then 'col1'
          when 2 then 'col2'
          when 3 then 'col3'
          when 4 then 'col4'
          end as col,
          case n 
          when 1 then col1
          when 2 then col2
          when 3 then col3
          when 4 then col4
          end as value
  from
 (
  select cast (col1 as varchar) col1,
         col2, 
         cast (col3 as varchar) col3,
         cast (col4 as varchar) col4,
         n
  from table1, rows
  ) x
查看更多
Anthone
3楼-- · 2019-02-17 22:15

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;
查看更多
劳资没心,怎么记你
4楼-- · 2019-02-17 22:16

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:

查看更多
登录 后发表回答