MSSQL查询将新表中的信息组合在一起

时间:2016-09-22 12:47:34

标签: sql sql-server

我的表:

servername: | FactName: | FactValue:
server01    | CPUcores  | 2
server01    | Memory    | 64GB
server01    | HDD01size | 50GB
server01    | HDD02size | 60GB
server01    | HDD03size | 70GB
server02    | CPUcores  | 4
server02    | Memory    | 32GB
server02    | HDD01size | 50GB
server02    | HDD02size | 60GB
server02    | OS        | Windows 2012 R2

我尝试使用MSSQL查询创建的是一个具有以下输出的新表:

servername:|CPUcores:|Memory:|HDD01size:|HDD02size:|HDD03size:|OS:   
server01   |2        |64GB   |50GB      |60GB      |70GB      | -     
server02   |4        |32GB   |50GB      |60GB      | -        |Windows 2012 R2

需要在获取数据期间动态创建列。 列名是:

SELECT DISTINCT [FactName]
FROM [table]

...添加了列" servername"。

我无法弄清楚实现这一目标的最佳方法。

1 个答案:

答案 0 :(得分:1)

这称为表格旋转。以下是使用conditional aggregation的一个选项:

select servername, 
    max(case when FactName = 'CPUcores' then FactValue end) as Cpucores,
    max(case when FactName = 'Memory' then FactValue end) as Memory,
    max(case when FactName = 'HDD01size' then FactValue end) as HDD01size,
    max(case when FactName = 'HDD02size' then FactValue end) as HDD02size,
    max(case when FactName = 'HDD03size' then FactValue end) as HDD03size,
    max(case when FactName = 'OS' then FactValue end) as OS
from yourtable 
group by servername

如果您不知道所有潜在的值/列,那么您需要使用dynamic sql