SQL子查询或联合

时间:2014-07-08 20:28:35

标签: sql sql-server sql-server-2008 subquery union

我正在使用SQL Server 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       |   Test1        |      Test2        |      Test3        |
+---------------------------------------------------------------------+
| 06/30/2014 |    443         |       456         |       487         | 
| 07/07/2014 |    1024        |       2056        |       2076        |
+---------------------------------------------------------------------+

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:1)

您可以使用PIVOT

执行此操作
SELECT *
FROM Table1
PIVOT (MAX(value) FOR label IN (Test1,Test2,Test3))pvt

演示:SQL Fiddle

使用您的查询:

SELECT *
FROM (SELECT [DATE_PULL] as d, [OWNER] as label, sum(VM_COUNT) as value 
      FROM [VCENTER_INFO_HIST] 
      GROUP BY OWNER, DATE_PULL
      )sub
PIVOT (MAX(value) FOR label IN (Test1,Test2,Test3))pvt

答案 1 :(得分:1)

使用pivot

SELECT * FROM [VCENTER_INFO_HIST]
pivot (sum(VM_COUNT) for OWNER in ([Test1], [Test2], [Test3])) as pvt