从 3 个不同的行计算一个值的 SQL 查询

时间:2021-06-29 00:35:24

标签: sql

col1       col2       cal_val

F          1879       1879
%          25         1409
$          -45        1454

第一行基本上输出回第 2 列中的条目 第二行基本上会计算第 1 行第 3 列中值的 25%,然后从之前的值中减去该值,即 1879-470 = 1409

我需要能够计算 1454 的最终值(基本上是从第二行输出值中减去)1409 - (-45) 这将等于 1454

2 个答案:

答案 0 :(得分:1)

您可以使用条件聚合:

select ( (sum(case when col1 = 'F' then col2 end) *
          sum(case when col1 = '%' then 1 - col2 / 100.0 end)
         ) -
         sum(case when col1 = '$' then col2 end)
       )
from t;

Here 是一个 db<>fiddle。

答案 1 :(得分:0)

create temporary table t_teble 
(
col1   text ,

col2   numeric ,

cal_val numeric );


insert into t_teble
select 'F',1879, 1879 union all
select '%',25,1409 union all
select '$',-45,1454;

select ( (sum(case when col1 = 'F' then col2 end) *
          sum(case when col1 = '%' then 1 - col2 / 100.0 end)
         ) -
         sum(case when col1 = '$' then col2 end)
       ), 
       (sum(case when col1 = 'F' then col2 end) *
          sum(case when col1 = '%' then 1 - col2 / 100.0 end)
         )
from t_teble;
相关问题