【问题标题】:SQL Math Equation with subqueries带有子查询的 SQL 数学方程
【发布时间】:2021-04-09 14:04:12
【问题描述】:

我坐在 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

【问题讨论】:

  • 整数除法?尝试在除法前乘以1.0。

标签: sql db2 subquery addition


【解决方案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'

【讨论】:

  • 但这给出了 3 个结果?我认为那是,我在做什么。条件聚合。我可以举一个简单的例子来了解我在哪里吗?
  • @MikeSeisbye 。 . .这将返回三列。这是一个条件聚合的例子。
  • 对不起.. 我还是不明白我要如何关闭这个?我只想要 1 个结果。不是三个。那么如何获得结果为 (rev + bud) / Bud2 ?
  • @MikeSeisbye 。 . .只需划分表达式。​​
猜你喜欢
  • 2016-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
相关资源
最近更新 更多