如何 SELECT 基于与该分组 SUM 的 AVG 进行比较的分组 SUM

How to SELECT based on grouped SUM that is compared to the AVG of that grouped SUM

我有一个 table 包含电影、类别和价格。 现在我只想 select 总价格(该类别下每部电影的所有价格总和)高于这些类别总价格的平均值的类别。 我已经能够找到总价格的平均值(感谢这个网站)但无法将它们组合在一起。 以下是查询:

-- 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
);

非常感谢任何帮助,谢谢!

使用 window 函数最容易解决这个问题:

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

尝试添加 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
);