我想做一个嵌套聚合,我可以选择是否聚合嵌套平均聚合的最大值,最小值或平均值。
我希望我的结果如下所示:(类型,MAX或MIN或嵌套AVG的AVG)
当前我有一个嵌套聚合查询,它只返回一个类型的最大平均价格,但我似乎也无法选择与该最大值对应的类型。
考虑表游戏(gameID,gameName,流派,价格),忽略gameID和gameName。
我现在拥有的嵌套查询:
SELECT MAX(avggenreprice) AS maxavg
FROM (
SELECT genre as subgenre, AVG(price) as avggenreprice
FROM games
GROUP BY
subgenre
) AS sub;
此查询的示例结果:
|maxavg|
| 368.22|
我希望它看起来像这样
| genre | maxavg |
| Racer | 368.22 |
我试过了:
SELECT sub.subgenre, MAX(avggenreprice) AS maxavg
FROM (
SELECT genre as subgenre, AVG(price) as avggenreprice
FROM games
GROUP BY
subgenre
) AS sub
;
但这只是给我错误代码1140
答案 0 :(得分:3)
select top 1 subgenre AS genre , AVG (price) As maxavg from games
group by subgenre order by AVG (price) desc
答案 1 :(得分:0)
SELECT subgenre, avggenreprice AS maxavg
FROM (
SELECT genre as subgenre, AVG(price) as avggenreprice
FROM games
GROUP BY
subgenre
) AS sub
ORDER BY avggenreprice DESC
Limit 1;
当MySQL不确定如何处理聚合函数并且需要显式的GROUP BY子句时,会出现1140代码。见(MySQL #1140 - Mixing of GROUP columns)。
对于您的案例,最简单的解决方案是使用排序DESC和限制1子句替换聚合函数max。
答案 2 :(得分:0)
只需使用ORDER BY
和LIMIT
即可。子查询不是必需的:
SELECT genre as subgenre, AVG(price) as avggenreprice
FROM games
GROUP BY subgenre
ORDER BY avggenreprice DESC
LIMIT 1;