使用备用行将两列合二为一

时间:2016-11-10 07:06:19

标签: sql-server tsql sql-server-2012

我有一个包含两列的表格,如下所示:

A   1
B   2
C   3
D   4
E   5 

我想将它们放到一列中,每列的数据都在新列的备用行中,如下所示:

A
1
B
2
C
3
D
4
E
5

4 个答案:

答案 0 :(得分:2)

我会使用UNION ALL,但这里是UNPIVOT替代方案:

CREATE TABLE #Table1(letter VARCHAR(10),Id VARCHAR(10))

INSERT INTO #Table1(letter ,Id )
SELECT 'A',1 UNION ALL
SELECT 'B',2 UNION ALL
SELECT 'C',3 UNION ALL
SELECT 'D',4 UNION ALL
SELECT 'E',5 


SELECT [value]
FROM #Table1
UNPIVOT
(
    [value] FOR [Column] IN ([Id], [letter])
) UNPVT


DROP TABLE #Table1;

答案 1 :(得分:1)

CREATE TABLE #Table1(Value VARCHAR(10),Id VARCHAR(10))

INSERT INTO #Table1(Value ,Id )
SELECT 'A',1 UNION ALL
SELECT 'B',2 UNION ALL
SELECT 'C',3 UNION ALL
SELECT 'D',4 UNION ALL
SELECT 'E',5 

;WITH _CTE (Name) AS
(
 SELECT Value [Name]
 FROM #Table1
 UNION ALL
 SELECT Id [Name]
 FROM #Table1
)
SELECT * FROM _CTE

答案 2 :(得分:1)

棘手的部分是备用行中的数据

select col2 
from 
 ( select col1, 1 as flag, col1 from tab
   union all
   select col1, 2,         col2 from tab
 ) as dt
order by col1, flag

但你为什么要尝试这样做呢?

答案 3 :(得分:1)

试试这个:

WITH CTE AS
(
  SELECT Col1Name Name,(ROW_NUMBER() OVER(ORDER BY(SELECT NULL))) RN 
  FROM TableName
  UNION 
  SELECT Col2Name Name,(ROW_NUMBER() OVER(ORDER BY(SELECT NULL)))+1 RN 
  FROM TableName
)
SELECT Name
FROM CTE
ORDER BY RN