在Sql中水平构建数据

时间:2018-10-25 06:25:34

标签: sql sql-server pivot

嗨,我有一个查询,该查询返回的数据如下

select
    n.Key, np.value
from
    Test1 np
    join Test2 n on n.Key = np.Key
where
    n.NodeKey = 10000002 && np.pKey in (4,6,7,10,12)

返回如下数据

Key            value
--------       ------
10000002        2
10000002        0
10000002        2
10000002       True
10000002        1

Test2是如下查找表

  Key      PKey           Value                                                                                                                                                                                                                                                    
---------------------------------------
10000002     4               2                                                                                                                                                                                                                                                                
10000002     6               0                                                                                                                                                                                                                                                                
10000002     7               2                                                                                                                                                                                                                                                                
10000002     10              True
10000002     12              1     

想更改查询,使其返回如下数据

NodeKey   Value1   Value2   Value3  Value4  Value5
--------------------------------------------------
10000002     2        0        2       True    1

能帮我吗?

2 个答案:

答案 0 :(得分:1)

您可以将pivot子句用作:

with t as
(
select i.* from Test2 i 
) 
select [Key] as 'NodeKey', 
       [4]   as 'Value1',
       [6]   as 'Value2',
       [7]   as 'Value3',
       [10]  as 'Value4',
       [12]  as 'Value5'
  from t
 pivot
 (
  max(Value) for PKey in ([4], [6], [7], [10], [12])    
 ) q;

NodeKey  Value1 Value2  Value3  Value4  Value5
-------- ------ ------  ------  ------ -------
10000002    2     0       2      True     1

Rextester Demo

答案 1 :(得分:0)

您可以尝试使用select n.Key, np.value, 'Value'+convert(varchar(2),ROW_NUMBER() over (partition by [key] order by [key])) as tmpCol into #tempTable --store result in tmp table from Test1 np join Test2 n on n.Key = np.Key where n.NodeKey = 10000002 && np.pKey in (4,6,7,10,12) 来水平结构化数据。 尝试下面的代码。

使用row_number()函数添加另一列并将整个结果存储在临时表中

select *
from 
(
  select [key], value,tmpCol
  from #tempTable
) src
pivot
(
  max(value)
  for tmpCol in (value1,value2,value3,value4,value5)
) piv;

然后使用下面的枢轴代码。

:scheme