oracle 中sql实现 同比 环比

sum和case when的结合使用

废话不多说,我们直接进行测试。

1.学生表数据

2.将学生按照性别区分

我们一般的写法就是使用group by进行分组。

select t.ssex, count(t.sname) from STUDENT t group by t.ssex;


如果我们需要求男生的人数是女生的多少倍怎么计算?

3.求男生的人数是女生的多少倍(sum和case when的结合使用)

  1. select "男生人数", "女生人数", "男生人数" / "女生人数" as 倍数

  2. from (select sum(case

  3. when t.ssex = '男' then

  4. 1

  5. else

  6. 0

  7. end) as "男生人数",

  8. sum(case

  9. when t.ssex = '男' then

  10. 1

  11. else

  12. 0

  13. end) as "女生人数"

  14. from STUDENT t)


通俗理解:就是将group by t.ssex的结果进行”行转列”操作
 

4.求同比和环比

1)同比概念

同比一般情况下是今年第n月与去年第n月比。
公式:同比增长率=(本期数-同期数)÷同期数×100%
一般理解:同比增长率=(今年第n月的数据-去年第n月数据)÷去年第n月数据×100%

2)同比测试

  • 收入表数据

  • 2019年5月收入同比
  1. select "本期收入", "同期收入", to_char(("本期收入" - "同期收入") / "同期收入",'fm99990.00') "同比"

  2. from (select sum(case

  3. when t.year = 2019 and month = 5 then

  4. t.money

  5. else

  6. 0

  7. end) as "本期收入",

  8. sum(case

  9. when t.year = 2018 and month = 5 then

  10. t.money

  11. else

  12. 0

  13. end) as "同期收入"

  14. from income t

  15. where t.name = '张三')

3)环比概念

环比,表示连续2个单位周期(比如连续两月)内的量的变化比。
公式:环比增长率=(本期数-上期数)/上期数×100%

4)环比测试

2019年5月收入环比

  1. select "本期收入", "上期收入", to_char(("本期收入" - "上期收入") / "上期收入",'fm99990.00') "环比"

  2. from (select sum(case

  3. when t.year = 2019 and month = 5 then

  4. t.money

  5. else

  6. 0

  7. end) as "本期收入",

  8. sum(case

  9. when t.year = 2019 and month = 4 then

  10. t.money

  11. else

  12. 0

  13. end) as "上期收入"

  14. from income t

  15. where t.name = '张三')


版权声明:本文为aiweijun4321原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。