如何在SQL中使用pivot更改行到列

时间:2017-02-14 13:48:41

标签: sql sql-server tsql

Input table

product_id  url                             key    value
1231201     http://sample.com/1231201.html  col1    2
1231201     http://sample.com/1231201.html  col2    10
1231201     http://sample.com/1231201.html  col3    3

我一直在使用下面提到的pivot Query:

SELECT   product_id,url,col1,col2,col3
FROM   [dbo].[table] 
PIVOT
(
       max(value)
       FOR [key] IN ([col1],[col2],[col3])
) AS P

我的输出如下所述

product_id  url                             col1    col2    col3
1231201     http://sample.com/1231201.html  NULL    2       NULL
1231201     http://sample.com/1231201.html  10      NULL    NULL
1231201     http://sample.com/1231201.html  NULL    NULL    3

我的预期输出:

product_id  url                             col1  col2 col3
1231201     http://sample.com/1231201.html  10     2    3
你可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

我怀疑你的表中有其他字段(即ID)

使用子查询隔离/限制您的字段到所需的PIVOT

select product_id,url,col1,col2,col3
From (Select product_id,url,[key],value from [dbo].[table] ) a
pivot (max(value) for [key] in ([col1],[col2],[col3])) as p

返回

product_id  url                             col1    col2    col3
1231201     http://sample.com/1231201.html  2       10      3

答案 1 :(得分:0)

您的表中可能还有一些其他列对这些行具有唯一值。

您可以选择在子查询中转动所需的列,然后应用数据透视。

试试这个:

select product_id,
    url,
    col1,
    col2,
    col3
from (
    select product_id,
        url,
        [key],
        value
    from [dbo].[table]
    ) t
PIVOT(max(value) for [key] in ([col1], [col2], [col3])) as P

演示:

with t(id, product_id , url ,[key] ,value) as (
select 1, 1231201 ,'http://sample.com/1231201.html',  'col1',   2  union all
select 2, 1231201 ,'http://sample.com/1231201.html',  'col2',   10 union all
select 3, 1231201 ,'http://sample.com/1231201.html',  'col3',   3 
)
select product_id,
    url,
    col1,
    col2,
    col3
from (
    select product_id,
        url,
        [key],
        value
    from t
    ) t
PIVOT(max(value) for [key] in ([col1], [col2], [col3])) as P

我明白了:

1231201 http://sample.com/1231201.html  2   10  3

查询:

with t(id, product_id , url ,[key] ,value) as (
select 1, 1231201 ,'http://sample.com/1231201.html',  'col1',   2  union all
select 2, 1231201 ,'http://sample.com/1231201.html',  'col2',   10 union all
select 3, 1231201 ,'http://sample.com/1231201.html',  'col3',   3 
)
select product_id,
    url,
    col1,
    col2,
    col3
from t
PIVOT(max(value) for [key] in ([col1], [col2], [col3])) as P

我明白了:

1231201 http://sample.com/1231201.html  2   NULL    NULL
1231201 http://sample.com/1231201.html  NULL    10  NULL
1231201 http://sample.com/1231201.html  NULL    NULL    3