MAX(DECODE()) 内带有 AVG 的表透视
大家好,我需要有关下面 SQL 的帮助。它不断为我的所有 a.name 提供单一输出:
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
使用枢轴(我想要的输出):
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
Hey guys I need help with the SQL below. It keeps giving me a single output for all of my 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;
OUTPUT: For example, I'll use drink brand name with a type of small, medium, large. I want the average of all the drinks in the stores across town.
Without using pivot
Drink | Size | Price
Dr. Pepper | Small | 1.00
Dr. Pepper | Medium | 1.50
Dr. Pepper | Large | 2.00
Using pivot (the output I want):
Drink | Small | Medium | Large
Dr. Pepper | 1.00 | 1.50 | 2.00
Mountain Dew | 0.50 | 0.75 | 1.25
The output I'm getting:
Drink | Small | Medium | Large
Dr. Pepper | 1.00 | 1.00 | 1.00
Mountain Dew | 1.00 | 1.00 | 1.00
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 (Oracle 9i+):
您的信息仍然缺少
DRINK
和SIZE
表之间的 JOIN 标准 - 我做了假设。如果没有条件,查询只会产生笛卡尔积 - 它永远不会产生您期望的输出。使用WITH 子句(Oracle 9i+):
PIVOT/UNPIVOT
Oracle 直到11g 才支持ANSI 语法。
Use (Oracle 9i+):
Your information still lacks the JOIN criteria between the
DRINK
andSIZE
tables - I made assumptions. Without the criteria, the query is just producing a cartesian product -- it will never produce the output you're expecting.Using WITH clause (Oracle 9i+):
PIVOT/UNPIVOT
The ANSI syntax wasn't supported in Oracle until 11g.
这是对我有用的解决方案 - 感谢 OMG Ponies 解决了一些问题。
我仍然不确定为什么 JOIN on 给了我这样的结果;我用 WHERE 替换了它,它工作了......很奇怪。
Here's the solution that worked for me - thanks to OMG Ponies for clearing some things up.
I'm still not sure why JOIN on gave me the results that it did; I replaced using WHERE, and it worked... weird.