2017-05-04 48 views
0

给定一个表,为每行取两列并显示两行的最佳方法是什么?这里有一个例子:sql - 将列转移到行

declare @t table (
    id int, 
    v1 nvarchar(max), 
    v2 nvarchar(max), 
    v3 nvarchar(max) 
) 
insert into @t 
select 0, 'hello', 'there', 'filler' 
union all select 1, 'hello', 'again', 'filler' 

有像这样的表:

0 hello there filler 
1 hello again filler 

...我想它看起来就像这样:

0 hello filler 
0 there filler 
1 hello filler 
1 again filler 

我试着做一个UNPIVOT,但鉴于我不需要清除所有列,这对我来说并不合适。

回答

0

您可以使用UNPIVOT到逆转置列的子集,而不是所有:

declare @t table (
id int, 
v1 nvarchar(max), 
v2 nvarchar(max), 
v3 nvarchar(max) 
) 
insert into @t 
select 0, 'hello', 'there', 'filler' 
union all select 1, 'hello', 'again', 'filler' 

SELECT id, v, v3 
FROM 
(
    SELECT id, v1, v2, v3 
    FROM @t 
) AS cp 
UNPIVOT 
(
    v FOR vs IN (v1, v2) 
) AS up; 
1

使用cross apply()values()

select t.id, v.col1, v.col2 
from @t t 
    cross apply (values (v1,v3),(v2,v3)) v(col1,col2) 

rextester演示:http://rextester.com/RMNJ58477

回报:

+----+-------+--------+ 
| id | col1 | col2 | 
+----+-------+--------+ 
| 0 | hello | filler | 
| 0 | there | filler | 
| 1 | hello | filler | 
| 1 | again | filler | 
+----+-------+--------+