需要查询减法和除法?

Need a query for subtraction and division?

我的table专栏是这样的

msd_mon,msd_yea,msd_sva...我要查询

SELECT
         (((        SELECT SUM(msd_sva)
        FROM  msdfc00 
        WHERE    msd_yea  IN
            (
            SELECT DISTINCT msd_yea
            FROM  msdfc00 
            )
)-(     SELECT SUM(msd_sva)
        FROM  msdfc00 
        WHERE    msd_yea  = '2016'
)* 100) / (     SELECT SUM(msd_sva)
        FROM  msdfc00 
        WHERE    msd_yea  = '2016'
)) AS thePerc,
         msd_yea
FROM  msdfc00 
WHERE    msd_fco  = 'KF'
 AND    msd_mon  = '11'
GROUP BY  msd_yea 

也就是说,我想从 2016 年 msd_mon 期间的 msd_sva 总和中减去 2017 年 msd_mon 期间的 msd_sva 总和.我的基准年是 2016 年。我只有 4 年到 2018 年。所以计算会像这样

for year 2016 value will be 0 for year 2017 it will be ((2017 - 2016)* 100 16) for year 2017 it will be ((2018 - 2016)* 100 16) for year 2017 it will be ((2019 - 2016)* 100 16)

有什么帮助吗?

使用条件聚合:

select sum(case when msd_yea = 2016 then msc_sva end) as sva_2016,
       sum(case when msd_yea = 2017 then msc_sva end) as sva_2017,
       sum(case when msd_yea = 2018 then msc_sva end) as sva_2018,
       sum(case when msd_yea = 2019 then msc_sva end) as sva_2019       
from msdfc00 
where msd_fco  = 'KF' and msd_mon  = '11';

您可以使用子查询进行最终计算:

select 0 as val_2016,
       (sva_2017 - sva_2016) * 100 / sva_2016 as val_2017,
       . . .
from (select sum(case when msd_yea = 2016 then msc_sva end) as sva_2016,
             sum(case when msd_yea = 2017 then msc_sva end) as sva_2017,
             sum(case when msd_yea = 2018 then msc_sva end) as sva_2018,
             sum(case when msd_yea = 2019 then msc_sva end) as sva_2019       
      from msdfc00 
      where msd_fco  = 'KF' and msd_mon  = '11'
     ) m;