72/72 = .0001572 - Yikes

时间:2014-03-03 17:43:01

标签: sql sql-server-2008

当我划分两个整数时,我得到的数字不正确。这是我的代码:

SELECT self_cert_pct_certified_vw.regn_bu,
   sum (self_cert_pct_certified_vw.certified) AS certified,
   sum (self_cert_pct_certified_vw.not_certified) AS not_certified,
   (sum (certified) * 1.0) AS numerator,

   (SELECT sum (certified) + sum (not_certified)) AS denomonator,
     (sum (certified))
   / CAST (
        (SELECT sum (certified) + sum (not_certified)
           FROM self_cert_pct_certified_vw) AS FLOAT)
   * 100.0

   AS pct_certified
FROM self_cert_pct_certified_vw
WHERE ( (     time_period = '2'
      AND self_cert_pct_certified_vw.regn_id = 'DCT'
      AND (certified > 0 OR not_certified > 0)))
GROUP BY self_cert_pct_certified_vw.regn_bu
ORDER BY self_cert_pct_certified_vw.regn_bu

以下是我得到的结果之一的示例:

regn_bu certified   not_certified   numerator   denomonator     pct_certified
DCT_CL  72        0                 72.0             72         0.0157270483388305

'certified'和'not_certified'都声明为int。我预计答案是100%而不是0.015 ......!

连连呢?

提前致谢

2 个答案:

答案 0 :(得分:2)

您正在比较苹果和橘子。为什么你再次为子比例做一个子查询?

相反,只需使用值:

SELECT self_cert_pct_certified_vw.regn_bu,
       sum(self_cert_pct_certified_vw.certified) AS certified,
       sum(self_cert_pct_certified_vw.not_certified) AS not_certified,
       (sum(certified) * 1.0) AS numerator,

       (sum(certified) + sum(not_certified)) AS denomonator,
       (sum(certified) * 1.0) / (sum(certified) + sum(not_certified)) * 100 as pct_certified
    . . . 

我很确定问题与聚合子查询中from子句中的计算有关。但是,我无法完全解释此问题,除非您在问题中未显示wheregroup by条款。

编辑:

嗯,完成的代码解释了问题。您想要的比例在一个组内。您计算的比率具有由子查询引起的所有记录的总数。

答案 1 :(得分:0)

尝试将所有INT列投放到浮动乘以1e0。除以两个整数值(列)会产生一个整数。乘以1.0将产生小数,而不是浮点数。