sql - 将列传输到行

时间:2017-05-04 20:50:18

标签: sql-server sql-server-2008

给定一个表,获取两列并为每一行显示两行的最佳方法是什么?这是一个例子:

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,但鉴于我不需要对所有列进行拆卸,这对我来说并不起作用。

2 个答案:

答案 0 :(得分:1)

values()select t.id, v.col1, v.col2 from @t t cross apply (values (v1,v3),(v2,v3)) v(col1,col2) 一起使用:

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

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

返回:

def Foo( a, b, c ):
    print( "Foo(%r, %r, %r)" % ( a, b, c ) )
    return 23456

def Bar( a, b ):
    print( "Bar(%r, %r)" % ( a, b ) )
    return 12345

LEGAL_COMMANDS = dict(   # map the names by which users will refer to commands, to the names you have given to the corresponding implementations in your code
    Foo=Foo,
    Bar=Bar,
)

def ExecList( lst ):
    cmd = lst[ 0 ]
    if cmd in LEGAL_COMMANDS:
        cmd = LEGAL_COMMANDS[ cmd ]
    else:
        raise ValueError( "%r is not a recognized command" % cmd )
    params = [ ( ExecList( param ) if param and isinstance( param, list ) else param ) for param in lst[ 1: ] ]
    return cmd( *params )

答案 1 :(得分: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;