汇总由PIVOT函数产生的列

时间:2018-07-17 05:13:53

标签: sql oracle analytics

我通过PIVOT函数使用以下查询:

SELECT *
    FROM (SELECT medicine_name, YEAR_OF_PURCHASE, profit_in_rupees FROM temp_1
         )
         PIVOT
            (AVG (NVL (profit_in_rupees, 0)) AS avg_profit
            FOR (year_of_purchase)
            IN ('2017' AS "2017", '2018' AS "2018"))
ORDER BY medicine_name;

这成功地给了我两个必填列2017_AVG_PROFIT2018_AVG_PROFIT,现在我必须在同一查询中再添加两个列。

1)我想添加一列,该列可以向我显示这两列之间的区别,即2018_AVG_PROFIT减去2017_AVG_PROFIT。 2)我还想知道使用上述列的值,与2018年相比,谁在我们2018年的利润中所占的百分比更低?

谢谢。

1 个答案:

答案 0 :(得分:1)

SELECT   medicine_name, 
         "2017_AVG_PROFIT", 
         "2018_AVG_PROFIT", 
         Nvl("2017_AVG_PROFIT", 0) - Nvl("2018_AVG_PROFIT", 0) AS "DIFF_AVG_PROFIT", 
         CASE "2017_AVG_PROFIT" 
                  WHEN 0 THEN NULL 
                  ELSE Cast(Nvl("2018_AVG_PROFIT", 0) AS DECIMAL(12,2)) / 
                    Cast("2017_AVG_PROFIT" AS DECIMAL(12,2))
         END AS "PERC_DIFF" 
FROM     ( 
                SELECT medicine_name, 
                       year_of_purchase, 
                       profit_in_rupees 
                FROM   temp_1 ) PIVOT (avg (nvl (profit_in_rupees, 0)) 
                                       AS avg_profit FOR (year_of_purchase) IN ('2017' AS "2017",
                                                                                                                '2018' AS "2018"))
ORDER BY medicine_name;

对于此示例架构/数据:

CREATE TABLE temp_1
(
  medicine_name varchar2(25), 
  year_of_purchase number(4),
  profit_in_rupees number(10)
);

INSERT INTO temp_1 (medicine_name, year_of_purchase, profit_in_rupees) VALUES ('m1', 2017, 100);
INSERT INTO temp_1 (medicine_name, year_of_purchase, profit_in_rupees) VALUES ('m2', 2017, 200);
INSERT INTO temp_1 (medicine_name, year_of_purchase, profit_in_rupees) VALUES ('m3', 2017, 300);
INSERT INTO temp_1 (medicine_name, year_of_purchase, profit_in_rupees) VALUES ('m1', 2018, 400);
INSERT INTO temp_1 (medicine_name, year_of_purchase, profit_in_rupees) VALUES ('m2', 2018, 100);
INSERT INTO temp_1 (medicine_name, year_of_purchase, profit_in_rupees) VALUES ('m3', 2018, 100);

它返回:

MEDICINE_NAME   2017_AVG_PROFIT  2018_AVG_PROFIT     DIFF_AVG_PROFIT     PERC_DIFF
m1              100              400                 -300                4
m2              200              100                 100                 0.5
m3              300              100                 200                 0.333