在MAX(DECODE())中使用AVG进行数据透视表

时间:2010-11-11 03:42:58

标签: sql oracle oracle10g pivot

嘿伙计我需要帮助下面的SQL。它一直为我的所有a.names提供一个输出:

 SELECT Drink.name,  
        MAX(DECODE(Size.type, 'Small', avg, NULL)) Small,
        MAX(DECODE(Size.type, 'Medium', avg, NULL)) Medium,
        MAX(DECODE(Size.type, 'Large', avg, NULL)) Large
 FROM Drink, Size (
             SELECT avg(Size.price) avg, Size.type, Drink.name FROM Drink, Size 
             GROUP BY Size.type, Drink.name )
 GROUP BY Drink.name
 ORDER BY Drink.name;

输出:例如,我将使用饮料品牌名称,小型,中型,大型。我想要整个城镇商店的所有饮料的平均值。

不使用数据透视

Drink       |   Size    |   Price
Dr. Pepper  |   Small   |    1.00
Dr. Pepper  |  Medium   |    1.50
Dr. Pepper  |   Large   |    2.00

使用pivot(我想要的输出):

Drink         |  Small    |   Medium  | Large
Dr. Pepper    |   1.00    |   1.50    |  2.00
Mountain Dew  |   0.50    |   0.75     |  1.25

我得到的输出:

Drink         |  Small    |   Medium  | Large
Dr. Pepper    |   1.00    |   1.00    |  1.00
Mountain Dew  |   1.00    |   1.00    |  1.00

2 个答案:

答案 0 :(得分:2)

使用(Oracle 9i +):

  SELECT x.name,
         MAX(CASE WHEN x.type = 'Small' THEN x.avg END) AS small,
         MAX(CASE WHEN x.type = 'Medium' THEN x.avg END) AS Medium,
         MAX(CASE WHEN x.type = 'Large' THEN x.avg END) AS Large
    FROM (SELECT d.name,
                 s.type, 
                 AVG(s.price) avg
            FROM DRINK d
            JOIN SIZE s ON s.size_id = d.size_id
        GROUP BY d.name, s.type) x
GROUP BY x.name

您的信息仍然缺少DRINKSIZE表之间的JOIN标准 - 我做了一些假设。没有标准,查询只是生成笛卡尔积 - 它永远不会产生您期望的输出。

使用WITH子句(Oracle 9i +):

WITH sample AS (
   SELECT d.name,
          s.type, 
          AVG(s.price) avg
     FROM DRINK d
     JOIN SIZE s ON s.size_id = d.size_id
 GROUP BY d.name, s.type)
  SELECT x.name,
         MAX(CASE WHEN x.type = 'Small' THEN x.avg END) AS small,
         MAX(CASE WHEN x.type = 'Medium' THEN x.avg END) AS Medium,
         MAX(CASE WHEN x.type = 'Large' THEN x.avg END) AS Large
    FROM sample x
GROUP BY x.name

PIVOT / UNPIVOT

直到11g,Oracle才支持ANSI语法。

答案 1 :(得分:1)

这是对我有用的解决方案 - 感谢OMG小马清除了一些东西。

SELECT x.NAME as "Drink", 
(MAX(DECODE(x.TYPE, 'Small', avg, NULL))) Small,
(MAX(DECODE(x."TYPE", 'Medium', avg, NULL))) Medium,
(MAX(DECODE(x."TYPE", 'Large', avg, NULL))) Large
FROM (
      SELECT Size."TYPE", Drink.NAME, Round(AVG(Size.price),2) avg 
      FROM Drink, Price 
      WHERE Drink.drink_id = Size.drink_id
      GROUP BY Size."TYPE", Drink.NAME) x
GROUP BY x.NAME
ORDER BY x.NAME;

我仍然不确定为什么JOIN会给我结果呢?我用WHERE替换了它,它很有用......很奇怪。