sql改写

原来的sql:

SELECT DATE_FORMAT(inventorydate,'%Y') AS YEAR,
               DATE_FORMAT(inventorydate,'%m') AS MONTH,
               commercecode,
               productcode,
               SUM(thisWeekInventory)
          FROM scm.scm_kc_weekinventory A 
         WHERE DATE_FORMAT(inventorydate,'%Y') = '2020'
           AND inventorydate = (SELECT MAX(inventorydate) 
                                  FROM scm.scm_kc_weekinventory b 
                                 WHERE a.year = b.year 
                                   AND a.month = b.month 
                                   AND a.commercecode = b.commercecode 
                                   AND a.productcode = b.productcode
                                )
         GROUP BY DATE_FORMAT(inventorydate,'%Y'),
               DATE_FORMAT(inventorydate,'%m'),
               commercecode,
               productcode;

改写后:

select inventorydate,
              commercecode,
               productcode,COMMERCENAME,
               SUM(thisWeekInventory)
             from (select inventorydate,DATE_FORMAT(inventorydate,'%Y'),DATE_FORMAT(inventorydate,'%m'),COMMERCENAME,thisWeekInventory,commercecode,productcode,
             dense_rank()OVER(PARTITION  BY DATE_FORMAT(inventorydate,'%Y'),DATE_FORMAT(inventorydate,'%m'),commercecode,productcode order by inventorydate desc) as rnk
             from scm.scm_kc_weekinventory
               where extract(year from inventorydate)='2020' )ma  where ma.rnk=1
               GROUP BY inventorydate,
               commercecode,
               productcode,COMMERCENAME;

改写前执行需要10几秒,改写后只需要2s。

posted @ 2020-05-22 08:19  5sdba  阅读(239)  评论(0编辑  收藏  举报