SUM两个不同的列在两个不同的表中按第三个表中的列分组

时间:2014-05-30 00:15:22

标签: sql sql-server sum

我可以让它在两个单独的查询中工作,但我不能同时使用两个连接来拥有所有三个列。有人可以帮帮我吗?我需要这样的输出:

+------------------------------------------------+
| CLUSTER_NAME   | TOTAL_UNITS   |ALLOCATED_UNITS|
+------------------------------------------------+
|    CLUSTER1    | 300           |25             |
+------------------------------------------------+
|    CLUSTER2    | 400           |45             |
+------------------------------------------- ----+

两个单独的查询正在运行:

查询1:

SELECT     CLUSTER_INFO.CLUSTER_NAME, sum(HOST_INFO.UNIT_COUNT) as 'TOTAL_UNITS'
FROM         CLUSTER_INFO INNER JOIN 
HOST_INFO ON HOST_INFO.CLUSTER_ID = CLUSTER_INFO.CLUSTER_ID
GROUP BY CLUSTER_INFO.CLUSTER_NAME

查询2:

SELECT     CLUSTER_INFO.CLUSTER_NAME, SUM(VM_INFO.UNIT_COUNT) as 'ALLOCATED_UNITS'
FROM         CLUSTER_INFO INNER JOIN 
VM_INFO ON CLUSTER_INFO.CLUSTER_ID = VM_INFO.CLUSTER_ID
GROUP BY CLUSTER_INFO.CLUSTER_NAME

表1(CLUSTER_INFO):

+--------------------------------+
| CLUSTER_NAME   | CLUSTER_ID    |
+--------------------------------+
|    CLUSTER1    | 1             |
+--------------------------------+
|    CLUSTER2    | 2             |
+--------------------------------+

表2(HOST_INFO):

+------------------------------------------------+
| HOST_NAME      | CLUSTER_ID    | UNIT_COUNT    |
+------------------------------------------------+
|    HOST1       | 1             | 150           |
+------------------------------------------------+
|    HOST2       | 1             | 150           |
+------------------------------------------------+
|    HOST3       | 2             | 200           |
+------------------------------------------------+
|    HOST4       | 2             | 200           |
+------------------------------------------------+

表3(VM_INFO):

+------------------------------------------------+
| VM_NAME        | CLUSTER_ID    | UNIT_COUNT    |
+------------------------------------------------+
|    VM1         | 1             | 10            |
+------------------------------------------------+
|    VM2         | 1             | 15            |
+------------------------------------------------+
|    VM3         | 2             | 20            |
+------------------------------------------------+
|    VM4         | 2             | 25            |
+------------------------------------------------+

http://www.sqlfiddle.com/#!2/5f9614/5

1 个答案:

答案 0 :(得分:1)

最安全的做法是使用两个子查询:

SELECT ci.CLUSTER_NAME, hi.TOTAL_UNITS, vi.ALLOCATED_UNITS
FROM CLUSTER_INFO ci LEFT JOIN 
     (SELECT hi.CLUSTER_ID, SUM(hi.UNIT_COUNT) as TOTAL_UNITS
      FROM HOST_INFO hi
      GROUP BY hi.CLUSTER_ID
     ) hi
     ON ci.CLUSTER_ID = hi.CLUSTER_ID LEFT JOIN
     (SELECT vi.CLUSTER_ID, SUM(vi.UNIT_COUNT) as ALLOCATED_UNITS
      FROM VM_INFO vi
      GROUP BY vi.CLUSTER_ID
     ) vi
     ON ci.CLUSTER_ID = vi.CLUSTER_ID ;

我引入了表别名以使查询更具可读性。并且,不要将列别名放在单引号中。您根本不需要引用这些名称。仅对日期和字符串常量使用单引号。

This SQL小提琴显示它正常工作。