Oracle OVER (PARTITION BY ) 灵活用法

OVER (PARTITION BY)开窗函数,可以根据每列进行各自的不同分组聚合,还可以根据条件排序,赛选出符合业务的数据项。

数据准备:

CREATE TABLE Merchant_sale_table AS
SELECT * FROM(
       SELECT to_date('20190501 10:12:11','yyyymmdd HH24:mi:ss') tradeDate, 'MID1' merchantId, 'MNM1' merchantName, 100 money FROM dual
       UNION ALL
       SELECT to_date('20190501 13:35:22','yyyymmdd HH24:mi:ss'), 'MID1', 'MNM11', 8 FROM dual
       UNION ALL
       SELECT to_date('20190501 05:45:49','yyyymmdd HH24:mi:ss'), 'MID1', 'MNM1', 12 FROM dual
       UNION ALL
       SELECT to_date('20190502 13:12:11','yyyymmdd HH24:mi:ss'), 'MID3', 'MNM3', 1000 FROM dual
       UNION ALL
       SELECT to_date('20190503 13:12:11','yyyymmdd HH24:mi:ss'), 'MID1', 'MNM1', 20 FROM dual
       UNION ALL
       SELECT to_date('20190503 13:12:11','yyyymmdd HH24:mi:ss'), 'MID2', 'MNM2', 50 FROM dual
);

要求:

将表以日期和商户号汇总,当天商户的交易额和交易量,并且商户名称以最新的交易中的商户名称为准。

实现:

SELECT TRADEDAY,MERCHANTID,MERCHANTNAME,totoalMoney,totoalCount FROM(
  SELECT TO_CHAR(T.TRADEDATE, 'yyyy-mm-dd') TRADEDAY,
              T.MERCHANTID,
              T.MERCHANTNAME,
              sum(nvl(t.money,0)) OVER (PARTITION BY TO_CHAR(T.TRADEDATE, 'yyyy-mm-dd'),T.MERCHANTID) totoalMoney,
              COUNT(1) OVER (PARTITION BY TO_CHAR(T.TRADEDATE, 'yyyy-mm-dd'),T.MERCHANTID) totoalCount,
              row_number() OVER (PARTITION BY TO_CHAR(T.TRADEDATE, 'yyyy-mm-dd'),T.MERCHANTID ORDER BY t.tradedate DESC) RN
  FROM FEE_COST.MERCHANT_SALE_TABLE T)
WHERE RN=1

结果:

执行计划:

Oracle OVER (PARTITION BY ) 灵活用法_第1张图片

根据执行计划可以看出在分组条件相同时,全表扫描只执行了一次。

你可能感兴趣的:(db)