假如資料表是這樣的:
2018年1月 100
2018年2月 200
2019年1月 300
2019年2月 400
我想實作:
2018年合計 2019年合計 同比增加
300 700 400
我知道可以用
select sum(a.資料),sum(b.資料), sum(b.資料-a.資料) from 表 as a,表 as b
where a.時間=2018 and b.時間=2019
這類方式來解決
但這樣需要自連接,資料量較大的時候會很卡
請問能不能做到直接先查2018,再查2019,最后一減
換句話說,橫著是until,豎著是啥啊?
多謝
uj5u.com熱心網友回復:
with xx as(select 1 as amount, 201801 as year
from dual
union all
select 2 as amount, 201802 as year
from dual
union all
select 11 as amount, 201901 as year
from dual
union all
select 2 as amount, 201902 as year
from dual)
select sum(amount) as tot_amount,
lag(sum(amount)) over(order by substr(year, 1, 4)) as last_tot_amount,
sum(amount) - nvl(lag(sum(amount)) over(order by substr(year, 1, 4)), sum(amount)) as minus_amount,
substr(year, 1, 4) as year
from xx
group by substr(year, 1, 4)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/24629.html
標籤:基礎和管理
