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

oracle 分析函數3

otto customer 所有 () tom 多個 from 存在 tmp

Top/Bottom N
First/Last
NTile

-- ①對所有客戶按訂單總額進行排名
-- ②按區域和客戶訂單總額進行排名
-- ③找出訂單總額排名前13位的客戶
-- ④找出訂單總額最高、最低的客戶
-- ⑤找出訂單總額排名前25%的客戶


-- 此處 null 被排到第一位 , 可以加 nulls last 把null的數據放到最後
select region_id, customer_id,
sum(customer_sales) cust_sales,
sum(sum(customer_sales)) over(partition by region_id) ran_total,
rank() 
over(partition by region_id order by sum(customer_sales) desc /* nulls last */) rank from user_order group by region_id, customer_id; -- 找出所有訂單總額排名前3的大客戶 select * from (select region_id, customer_id, sum(customer_sales) cust_total, rank() over(order by sum(customer_sales) desc NULLS LAST) rank
from user_order group by region_id, customer_id) where rank <= 3; -- 找出每個區域訂單總額排名前3的大客戶 select * from (select region_id, customer_id, sum(customer_sales) cust_total, sum(sum(customer_sales)) over(partition by region_id) reg_total, rank() over(partition by region_id order by sum
(customer_sales) desc NULLS LAST) rank from user_order group by region_id, customer_id) where rank <= 3; -- min keep first last 找出訂單總額最高、最低的客戶 -- Min只能用於 dense_rank -- min 函數的作用是用於當存在多個First/Last情況下保證返回唯一的記錄, 去掉會出錯 -- keep的作用。告訴Oracle只保留符合keep條件的記錄。 select min(customer_id) keep (dense_rank first order by sum(customer_sales) desc) first, min(customer_id) keep (dense_rank last order by sum(customer_sales) desc) last from user_order group by customer_id; -- 出訂單總額排名前1/5的客戶 ntile -- 1.將數據分成5塊 select region_id,customer_id, sum(customer_sales) sales, ntile(5) over(order by sum(customer_sales) desc nulls last) tile from user_order group by region_id, customer_id; -- 2.提取 tile=1 的數據 select * from (select region_id,customer_id, sum(customer_sales) sales, ntile(5) over(order by sum(customer_sales) desc nulls last) tile from user_order group by region_id, customer_id) where tile = 1; -- cust_nbr,month 為主鍵, 去重,只留下month最大的記錄 -- 查找 cust_nbr 相同, month 最大的記錄 select cust_nbr, max(month) keep(dense_rank first order by month desc) max_month from orders_tmp group by cust_nbr; -- 去重, cust_nbr,month 為主鍵, cust_nbr 相同,只留下month最大的記錄 delete from orders_tmp2 where (cust_nbr, month) not in (select cust_nbr, max(month) keep(dense_rank first order by month desc) max_month from orders_tmp2 tb group by cust_nbr)

oracle 分析函數3