如何根据与该 groupby SUM 的 AVERAGE 进行比较的 groupby SUM 进行选择
Posted
技术标签:
【中文标题】如何根据与该 groupby SUM 的 AVERAGE 进行比较的 groupby SUM 进行选择【英文标题】:How to SELECT based on grouped SUM that is compared to the AVG of that grouped SUM 【发布时间】:2021-03-12 08:34:09 【问题描述】:我有一张包含电影、类别和价格的表格。 现在我只想选择总价格(该类别下每部电影的所有价格总和)高于这些类别总价格平均值的类别。 我已经能够找到总价格的平均值(感谢这个网站),但无法将它们组合在一起。 以下是查询:
-- Return the average sums of the price per category
SELECT AVG(sum_price)
FROM
(
SELECT category, sum(price) AS sum_price
FROM film_list
GROUP BY category
) AS inner_query;
-- Return category and its total price
SELECT category, SUM(price)
FROM film_list
GROUP BY category;
--[Error] Return only the category with sums of price larger than the average of sum of prices
SELECT category, SUM(price)
FROM film_list
WHERE SUM(price) >
(
SELECT AVG(sum_price)
FROM
(
SELECT category, sum(price) AS sum_price
FROM film_list
GROUP BY category
) AS inner_query
);
任何帮助将不胜感激,谢谢!
【问题讨论】:
请提供样本数据和期望的结果。 可能您想使用HAVING
子句。 dev.mysql.com/doc/refman/5.6/en/group-by-handling.html
【参考方案1】:
使用窗口函数最容易解决这个问题:
SELECT c.*
FROM (SELECT category, SUM(price) AS sum_price,
AVG(SUM(price)) OVER () as avg_total_price
FROM film_list
GROUP BY category
) c
WHERE sum_price > avg_total_price
【讨论】:
它有效!刚刚查找了 OVER 子句,现在我知道了窗口函数。谢谢!【参考方案2】:尝试添加group by
,然后使用having
SELECT category, SUM(price)
FROM film_list
GROUP BY category
HAVING SUM(price) >
(
SELECT AVG(sum_price)
FROM
(
SELECT category, sum(price) AS sum_price
FROM film_list
GROUP BY category
) AS inner_query
);
【讨论】:
以上是关于如何根据与该 groupby SUM 的 AVERAGE 进行比较的 groupby SUM 进行选择的主要内容,如果未能解决你的问题,请参考以下文章