1. 程式人生 > >oracle 分析函數4

oracle 分析函數4

value 統計 有時 blog 例如 平均值 ice 範圍 bold

窗口函數
first_value/last_value
rows between ...preceding and ... following
range between interval
current row
lag(sum(tot_sales),1), lead

-- ①列出每月的訂單總額以及全年的訂單總額
-- ②列出每月的訂單總額以及截至到當前月的訂單總額
-- ③列出上個月、當月、下一月的訂單總額以及全年的訂單總額
-- ④列出每天的營業額及一周來的總營業額
-- ⑤列出每天的營業額及一周來每天的平均營業額

-- ①通過指定一批記錄:例如從當前記錄開始直至某個部分的最後一條記錄結束
-- ②通過指定一個時間間隔:例如在交易日之前的前30天 -- ③通過指定一個範圍值:例如所有占到當前交易量總額5%的記錄 -- 列出每月的訂單總額以及全年的訂單總額 1.實現方法1 select month, sum(tot_sales) month_sales, sum(sum(tot_sales)) over (order by month rows between unbounded preceding and unbounded following) total_sales from orders group by month; 2.實現方法2 select month, sum
(tot_sales) month_sales, sum(sum(tot_sales)) over(/*order by month*/) all_sales -- 加上Order by month , 則數逐條記錄遞增 from orders group by month; -- 列出每月的訂單總額以及截至到當前月的訂單總額 1.實現方法1 select month, sum(tot_sales) month_sales, sum(sum(tot_sales)) over(order by month rows between unbounded preceding and current row) current_total_sales
from orders group by month; 2.實現方法2 select month, sum(tot_sales) month_sales, sum(sum(tot_sales)) over(order by month) all_sales -- 加上Order by month , 則是前面記錄累加到當前記錄 from orders group by month; -- 有時可能是針對全年的數據求平均值,有時會是針對截至到當前的所有數據求平均值。很簡單,只需要將: -- sum(sum(tot_sales))換成avg(sum(tot_sales))即可。 -- 統計當天銷售額和五天內的平均銷售額 range between interval select trunc(order_dt) day, sum(sale_price) daily_sales, avg(sum(sale_price)) over (order by trunc(order_dt) range between interval 2 day preceding and interval 2 day following) five_day_avg from cust_order where sale_price is not null and order_dt between to_date(01-jul-2001,dd-mon-yyyy) and to_date(31-jul-2001,dd-mon-yyyy) -- 顯示當前月、上一個月、後一個月的銷售情況,以及每3個月的銷售平均值 select month, first_value(sum(tot_sales)) over (order by month rows between 1 preceding and 1 following) prev_month, sum(tot_sales) monthly_sales, last_value(sum(tot_sales)) over (order by month rows between 1 preceding and 1 following) next_month, avg(sum(tot_sales)) over (order by month rows between 1 preceding and 1 following) rolling_avg from orders_tmp where year = 2001 and region_id = 6 group by month order by month; -- 顯示當月的銷售額和上個月的銷售額 -- first_value(sum(tot_sales) over (order by month rows between 1 precedingand 0 following)) -- lag(sum(tot_sales),1)中的1表示以1月為間隔基準, 對應為lead select month, sum(tot_sales) monthly_sales, lag(sum(tot_sales), 1) over (order by month) prev_month_sales from orders_tmp where year = 2001 and region_id = 6 group by month order by month;

oracle 分析函數4