带有子查询的 SQL 数学方程

问题描述

我坐在 DB2 服务器上,试图计算 KPI 卡。这是一个相当简单的等式..

今年的收入 + 余下的预算/总预算

但是每当我开始除法时,我都会得到 1 作为结果。我在看什么?我尝试了不同的方法。下面是我最大的希望:-D

select ((x.Rev+ y.Budget) / t.Budget)
from
(
        select sum(oms) as Rev from vislib.faktura
        Where Origin = 'MOVEX'
        AND yy = 2021
        AND SMCD = '2294'
        AND IVNO <> 0
) x
join
(
       select sum(TASTBUDOMS) as Budget  from vislib.faktura
        where ORIGIN = 'TASTBUD'
        AND yy = 2021
        AND MM > 3
        AND SMCD = '2294'
) y on 1=1
join
(
       select sum(TASTBUDOMS) as Budget from vislib.faktura
        where ORIGIN = 'TASTBUD'
        AND yy = 2021
        AND SMCD = '2294'
) t on 1=1

解决方法

使用条件聚合来获取您想要的值:

select sum(case when Origin = 'MOVEX' and ivno <> 0 then oms end) as Rev,sum(case when Origin = 'TASTBUD' and mm > 3 then TASTBUDOMS end) as budget,sum(case when Origin = 'TASTBUD' then TASTBUDOMS end) as budget2      
from vislib.faktura
Where yy = 2021 and
      SMCD = '2294'

然后您可以组合这些:

select ( (sum(case when Origin = 'MOVEX' and ivno <> 0 then oms end) +
          sum(case when Origin = 'TASTBUD' and mm > 3 then TASTBUDOMS end)
         ) /
         sum(case when Origin = 'TASTBUD' then TASTBUDOMS end)
       ) as ratio      
from vislib.faktura
Where yy = 2021 and
      SMCD = '2294'