具有内连接和条件的SQL求和函数

时间:2013-09-20 20:34:51

标签: sql sql-server-2008 sum

我有以下查询产生波纹表:

  SELECT 
    memcpu.[ID]
  , memcpu.[DNS_NAME]
  , memcpu.[MEM_SIZE_MB] 
  , hdd.PATH
  , hdd.CAPACITY 
  FROM [VCenterServer].[dbo].[VPX_VM] AS memcpu
  INNER JOIN [VCenterServer].[dbo].[VPX_GUEST_DISK] AS hdd
  ON memcpu.ID = hdd.VM_ID
  GROUP BY 
    memcpu.[ID]
  , memcpu.[DNS_NAME] 
  , memcpu.[MEM_SIZE_MB]
  , hdd.PATH
  , hdd.CAPACITY
  ;

TABLE:

ID  DNS_NAME    MEM_SIZE_MB PATH    CAPACITY
27  name27      2048        C:\     42947571712
28  name28      4096        C:\     42947571712
28  name28      4096        E:\     134214578176
37  name37      6144        C:\     42947571712
38  name38      2048        C:\     42947571712
39  name39      8192        C:\     145077825536

我想知道如何使用所有相同PATH变量的条件对ID进行SUM。基本上总结每个虚拟机的存储空间,以便我可以看到内存和总存储空间的配置。

Desired TABLE(注意ID 28,它有C:和E:总结):

问题是CAPACITY被定义为nvarchar(21)

ID  DNS_NAME    MEM_SIZE_MB     CAPACITY
27  name27      2048            42947571712
28  name28      4096            177162149888
37  name37      6144            42947571712
38  name38      2048            42947571712
39  name39      8192            145077825536

2 个答案:

答案 0 :(得分:3)

PATH子句中删除CAPACITYGROUP BY字段,并在CAPACITY中对SELECT求和。

这样的事情应该做:

SELECT 
  memcpu.[ID]
, memcpu.[DNS_NAME]
, memcpu.[MEM_SIZE_MB] 
, sum(convert(decimal(21, 0), hdd.CAPACITY))
FROM [VCenterServer].[dbo].[VPX_VM] AS memcpu
INNER JOIN [VCenterServer].[dbo].[VPX_GUEST_DISK] AS hdd
ON memcpu.ID = hdd.VM_ID
GROUP BY 
  memcpu.[ID]
, memcpu.[DNS_NAME] 
, memcpu.[MEM_SIZE_MB]
;

答案 1 :(得分:0)

SELECT 
  memcpu.[ID]
 , memcpu.[DNS_NAME]
 , memcpu.[MEM_SIZE_MB] 

 , sum(hdd.CAPACITY ) CAPACITY 
FROM [VCenterServer].[dbo].[VPX_VM] AS memcpu
INNER JOIN [VCenterServer].[dbo].[VPX_GUEST_DISK] AS hdd
ON memcpu.ID = hdd.VM_ID
GROUP BY 
 memcpu.[ID]
 , memcpu.[DNS_NAME] 
 , memcpu.[MEM_SIZE_MB] ;