如何平均一组的最小值
How to average the minimums of a group by
如果我select每组的最小值:
SELECT MIN(price) FROM Products GROUP BY category
我怎样才能得到这个最小值的平均值?我明白
SELECT AVG(MIN(price)) FROM Products GROUP BY category
行不通。有什么帮助吗?
您需要分两步完成:
WITH min_prices as
(
SELECT category, MIN(price) as min_price
FROM Products
GROUP BY category
)
SELECT category, AVG(min_price) as avg_min_price
FROM min_prices
GROUP BY category
您必须找到所有类别的最小值,然后对它们应用平均函数。
select avg(m) as AvgOfAllMins from
(
select category,min(price) as m from products
group by category) T;
查看 db-fiddle 的结果。
如果我select每组的最小值:
SELECT MIN(price) FROM Products GROUP BY category
我怎样才能得到这个最小值的平均值?我明白
SELECT AVG(MIN(price)) FROM Products GROUP BY category
行不通。有什么帮助吗?
您需要分两步完成:
WITH min_prices as
(
SELECT category, MIN(price) as min_price
FROM Products
GROUP BY category
)
SELECT category, AVG(min_price) as avg_min_price
FROM min_prices
GROUP BY category
您必须找到所有类别的最小值,然后对它们应用平均函数。
select avg(m) as AvgOfAllMins from
(
select category,min(price) as m from products
group by category) T;
查看 db-fiddle 的结果。