sql中聚合函数的区别

时间:2012-07-06 08:50:28

标签: sql oracle

我想知道为什么以下查询没有正确检索两个聚合函数(sum)之间的差异?

SELECT 
    epa.status as Status,
    sum(equip_port_usage.total_nbr_ports) as Total,
    sum(equip_port_usage.NBR_PORTS_ASSIGNED) as Used,
    sum(equip_port_usage.NBR_PORTS_ASSIGNED)
      - sum(equip_port_usage.NBR_PORTS_ASSIGNED) as Difference
  FROM site_inst
  INNER JOIN site_attr_settings
     ON site_attr_settings.site_inst_id = site_inst.site_inst_id
  INNER JOIN epa on epa.site_inst_id=site_inst.site_inst_id
  INNER JOIN equip_inst ON equip_inst.site_inst_id=site_inst.site_inst_id
  INNER JOIN equip_port_usage
     ON equip_port_usage.equip_inst_id=equip_inst.equip_inst_id
WHERE site_inst.SITE_HUM_ID = 'CLEUS'
GROUP BY epa.status;

输出如下

Ok        303876  10276     0
Faulty     19044    644     0
Reserved   19872    672     0

我期待它

Ok        303876  10276  293600
Faulty     19044    644   18400
Reserved   19872    672   19200

2 个答案:

答案 0 :(得分:2)

这是代码中的复制和粘贴失败。 你正在计算

sum(equip_port_usage.NBR_PORTS_ASSIGNED)
 - sum(equip_port_usage.NBR_PORTS_ASSIGNED)

始终为0.

尝试:

SELECT 
    epa.status as Status,
    sum(equip_port_usage.total_nbr_ports) as Total,
    sum(equip_port_usage.NBR_PORTS_ASSIGNED) as Used,
    sum(equip_port_usage.total_nbr_ports)
     - sum(equip_port_usage.NBR_PORTS_ASSIGNED) as Difference
  FROM site_inst
  INNER JOIN site_attr_settings
     ON site_attr_settings.site_inst_id = site_inst.site_inst_id
  INNER JOIN epa ON epa.site_inst_id=site_inst.site_inst_id
  INNER JOIN equip_inst ON equip_inst.site_inst_id=site_inst.site_inst_id
  INNER JOIN equip_port_usage
     ON equip_port_usage.equip_inst_id=equip_inst.equip_inst_id
 WHERE site_inst.SITE_HUM_ID = 'CLEUS'
 GROUP BY epa.status

答案 1 :(得分:0)

你将两个相同的列相加,然后减去两个结果,所以当然你总是得到0