将多列连接成一行

时间:2014-07-08 17:42:38

标签: sql sql-server sql-server-2008

使用MSSQL 2008并且遇到麻烦以我需要的方式返回行。以下查询返回以下数据。

查询:

SELECT [DATE_PULL] as d, [OWNER] as label, sum(VM_COUNT) as value 
FROM [VCENTER_INFO_HIST] 
GROUP BY OWNER, DATE_PULL

+-------------------------------------------------+
|    D       |   label        |  value            |
+-------------------------------------------------+
| 06/30/2014 |    Test1       |       443         |
+-------------------------------------------------+
| 06/30/2014 |    Test2       |       456         |
+-------------------------------------------------+
| 06/30/2014 |    Test3       |       487         |
+-------------------------------------------------+
| 07/07/2014 |    Test1       |       1024        |
+-------------------------------------------------+
| 07/07/2014 |    Test2       |       2056        |
+-------------------------------------------------+
| 07/07/2014 |    Test3       |       2076        |
+-------------------------------------------------+

我需要输出看起来像这样:

+---------------------------------------------------+
|    D       |                value                 |
+---------------------------------------------------+
| 06/30/2014 | Test1: 443, Test2: 456, Test3: 487   |
+---------------------------------------------------+
| 07/07/2014 | Test1: 1024, Test2: 2056, Test3: 2076|
+---------------------------------------------------+

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:3)

您可以使用SQL Server中的STUFFFOR XML PATH功能,如下所示:

select distinct [DATE_PULL] as D, 
    stuff((select ', ' + [OWNER] + ': ' + convert(varchar(20), sum(VM_COUNT)) + '' as [text()]
                from [VCENTER_INFO_HIST] c where c.[DATE_PULL] = v.[DATE_PULL]
                group by c.[OWNER] 
                for xml path('')), 1, 1, '') as value
    from [VCENTER_INFO_HIST] v

请记住,随着数据集的增长,这可能有点低效,因为我们正在进行子查询,但这是我知道如何执行上述操作的唯一方法。如果有另一种方式,有人也会指出我正确的方向......

无论如何,您可以找到有关STUFF hereFOR XML here的更多信息。虽然,如果您希望它们是独立的列,Kris在评论中提供的使用PIVOT的答案更可能是您想要的。