oracle中sum和case when的結合使用(求同比和環比)

sum和case when的結合使用

廢話很少說,咱們直接進行測試。測試

1.學生表數據

2.將學生按照性別區分

咱們通常的寫法就是使用group by進行分組。3d

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


若是咱們須要求男生的人數是女生的多少倍怎麼計算?code

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

select "男生人數", "女生人數", "男生人數" / "女生人數" as 倍數
  from (select sum(case
                     when t.ssex = '男' then
                      1
                     else
                      0
                   end) as "男生人數",
               sum(case
                     when t.ssex = '男' then
                      1
                     else
                      0
                   end) as "女生人數"
          from STUDENT t)


通俗理解:就是將group by t.ssex的結果進行」行轉列」操做

blog

4.求同比和環比

1)同比概念

同比通常狀況下是今年第n月與去年第n月比。
公式:同比增加率=(本期數-同期數)÷同期數×100%
通常理解:同比增加率=(今年第n月的數據-去年第n月數據)÷去年第n月數據×100%get

2)同比測試

  • 收入表數據
  • 2019年5月收入同比
select "本期收入", "同期收入", to_char(("本期收入" - "同期收入") / "同期收入",'fm99990.00') "同比"
  from (select sum(case
                     when t.year = 2019 and month = 5 then
                      t.money
                     else
                      0
                   end) as "本期收入",
               sum(case
                     when t.year = 2018 and month = 5 then
                      t.money
                     else
                      0
                   end) as "同期收入"
          from income t
         where t.name = '張三')

3)環比概念

環比,表示連續2個單位週期(好比連續兩月)內的量的變化比。
公式:環比增加率=(本期數-上期數)/上期數×100%select

4)環比測試

2019年5月收入環比im

select "本期收入", "上期收入", to_char(("本期收入" - "上期收入") / "上期收入",'fm99990.00') "環比"
  from (select sum(case
                     when t.year = 2019 and month = 5 then
                      t.money
                     else
                      0
                   end) as "本期收入",
               sum(case
                     when t.year = 2019 and month = 4 then
                      t.money
                     else
                      0
                   end) as "上期收入"
          from income t
         where t.name = '張三')

轉載自https://liuhangs.com/?p=33d3

相關文章
相關標籤/搜索