ORACLE pl / sql每季度输出前3个最赚钱的产品

时间:2018-05-17 14:29:52

标签: database oracle oracledb

我试图每季度输出前3个产品,这应该是总共12行,因为每季度有3个顶级产品。 最接近的输出是下面提供的输出我不知道如何喜欢每季度分区

SELECT * FROM (SELECT QUARTER, PRODUCT_NAME, SUM(QUANTITY) "QTY_SOLD", SALES, SUM(PROFIT) "PROFIT_GENERATED" FROM DELIVERIES_FACT 
    WHERE EXTRACT(YEAR from SHIP_DATE) = 2015 GROUP BY  QUARTER, PRODUCT_NAME, SALES ORDER BY "PROFIT_GENERATED" DESC)
    WHERE rownum <= 3

获得

的输出

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

我已经写了这个从SHIP_DATE提取日历季度的SQL;你可以根据需要进行调整。

同样,RANK(),ROW_NUMBER()和DENSE_RANK()都是不同的;您可能希望尝试使用每个分析函数来查看哪个最适合您的数据并按照您希望的方式处理。

SELECT * 
  FROM (SELECT RANK() OVER (PARTITION BY SHIP_QUARTER 
                            ORDER BY PROFIT_GENERATED desc) AS PROFIT_RANK_BY_Q, 
               ORIG.* 
          FROM
               (SELECT EXTRACT(QUARTER from SHIP_DATE) AS SHIP_QUARTER, 
                       PRODUCT_NAME, 
                       SUM(QUANTITY) "QTY_SOLD", SALES, SUM(PROFIT) "PROFIT_GENERATED" 
                  FROM DELIVERIES_FACT 
                 WHERE EXTRACT(YEAR from SHIP_DATE) = 2015 
                 GROUP BY EXTRACT(QUARTER from SHIP_DATE), PRODUCT_NAME, SALES 
               )
       )
 WHERE PROFIT_RANK_BY_Q <= 3
 order by SHIP_QUARTER, PROFIT_RANK_BY_Q