SQL将具有UniqueID +多个键值对的表转换为行

时间:2018-01-10 00:20:14

标签: sql-server

我有一张数据表:

UniqueID |key1 |value1|key2|value2|
123      |1    |a     |2   |c 
234      |1    |b     |2   |d

我希望它是:

UniqueID|key|value
123     |1  |a
234     |1  |b
123     |2  |c
234     |2  |d

尝试在SQL Server中执行此操作。

1 个答案:

答案 0 :(得分:2)

使用UNION ALL

SELECT UniqueID, key = key1, value = value1 from table
union all
SELECT UniqueID, key = key2, value = value2 from table

[编辑]:以下是如何制作Dynamic

的示例脚本

假设:必须有一个键/值对

create table Table1
(
    UniqueID    int,
    key1        int,
    value1      varchar(10),
    key2        int,
    value2      varchar(10),
    key3        int,
    value3      varchar(10)
)

insert into Table1 select 1, 1, 'a', 2, 'b', 3, 'c'
insert into Table1 select 2, 5, 'e', 6, 'f', 7, 'g'


declare @sql    nvarchar(max)

; with 
col_key as
(
    select  key_col = c.name, rn = row_number() over (order by c.name)
    from    sys.columns c
    where   c.object_id = object_id('Table1')
    and c.name  like 'key%'
),
col_val as
(
    select  val_col = c.name, rn = row_number() over (order by c.name)
    from    sys.columns c
    where   c.object_id = object_id('Table1')
    and     c.name  like 'value%'
)
select  @sql    = isnull(@sql + ' UNION ALL' + char(13), '')
                + 'SELECT UniqueID, [key] = ' + k.key_col + ', [value] = ' + v.val_col + ' '
                + 'FROM Table1'
from    col_key k
        inner join col_val v    on  k.rn    = v.rn

print   @sql

exec    sp_executesql @sql

drop table Table1