1

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

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

任何帮助将不胜感激,谢谢!

4

2 回答 2

0

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

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
于 2020-11-30T12:08:47.140 回答
0

尝试添加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
);
于 2020-11-30T12:09:04.930 回答