簡體   English   中英

SQL查詢以獲取當前和去年的銷售額及其在oracle中的差異

[英]SQL query to get current and last year sales and their difference in oracle

我有下表銷售:

year total_sale
2015 23000
2016 25000
2017 34000
2018 32000
2019 33000

這必須是結果

year current_total_sale previous_total_sale difference
2015 23000              NULL                NULL
2016 25000              23000               2000
2017 34000              25000               9000
2018 32000              34000               -2000
2019 33000              32000               1000

使用滯后查詢所需結果 -

select year_1, total_sale as current_total_sale, 
lag(total_sale) over (order by null) as previous_total_sale,
total_sale - lag(total_sale) over (order by null) difference
from sales;

DB小提琴在這里

自連接,將表連接到自身。

select a.year, a.total_sale as current_total_sale, b.total_sale as prev_total_sale,
b.total_sale - a.total_sale as difference
from have as a
left have as b
on a.year = b.year+1
order by 1;
CREATE TABLE sales (yr,total_sale) AS
SELECT 2015, 23000 FROM DUAL UNION ALL 
SELECT 2016, 25000 FROM DUAL UNION ALL 
SELECT 2017, 34000 FROM DUAL UNION ALL 
SELECT 2018, 32000 FROM DUAL UNION ALL 
SELECT 2019, 33000 FROM DUAL; 

select curr.yr, curr.total_sale, prev.total_sale as previous_total_sale, 
curr.total_sale - prev.total_sale difference
from sales curr
LEFT JOIN sales prev ON curr.yr = prev.yr + 1
ORDER BY curr.yr;

YR  TOTAL_SALE  PREVIOUS_TOTAL_SALE DIFFERENCE
2015    23000    -   - 
2016    25000   23000   2000
2017    34000   25000   9000
2018    32000   34000   -2000
2019    33000   32000   1000

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM