联合列值分为一行

时间:2014-05-28 13:24:07

标签: sql sql-server pivot

我有一个具有这种结构的平板电脑:

Usr    Key        Value
Peter   Address    78 Street
Peter   Number     123456
Peter   Sport      Rugby
Peter   Document   ABCDE

我想对此进行查询:

NAME  Address   Number Sport Document
Peter 78 Street 123456 Rugby ABCDE

谁能帮帮我? See image for result

2 个答案:

答案 0 :(得分:1)

如果每个用户的每个密钥只有一个值:

select P.*
from Table1 as t
pivot (
    max(Value)
    for [Key] in ([Address], [Number], [Sport], [Document])
) as P

select
    t.Usr,
    max(case when t.[Key] = 'Address' then t.[Value] end) as Address,
    max(case when t.[Key] = 'Number' then t.[Value] end) as Number,
    max(case when t.[Key] = 'Sport' then t.[Value] end) as Sport,
    max(case when t.[Key] = 'Document' then t.[Value] end) as Document
from Table1 as t
group by t.Usr

<强> sql fiddle demo

答案 1 :(得分:0)

您应该查看此link以获取有关PIVOT语句的更多信息。至于你的问题,这是一个如何做到的例子:

--create temp table and populate it
SELECT 'NAME' AS [KEY], 'Peter' AS VALUE
INTO #tmp
UNION ALL
SELECT 'Address' AS [KEY], '78' AS VALUE
UNION ALL
SELECT 'Number' AS [KEY], '1' AS VALUE
UNION ALL
SELECT 'Sport' AS [KEY], 'Rugby' AS VALUE
UNION ALL
SELECT 'Document' AS [KEY], 'qwretz' AS VALUE

--check what's in here
SELECT [KEY], VALUE FROM #tmp

--pivot
SELECT [NAME], [Address], [Number], [Sport], [DOCUMENT]
FROM
( SELECT [KEY], VALUE FROM #tmp) AS SourceTable
PIVOT
( MAX(VALUE)
FOR [KEY] IN ([NAME], [Address], [Number], [Sport], [DOCUMENT])
) AS PivotTable