我正在尝试检索有关商店的详细信息,这些商店的平均产品价格高于表中所有商店的平均价格。
到目前为止,我有以下代码:
select StoreID, count(ProductID) from Products
where (select avg(Price) from Products group by StoreID) > (select avg(Price) from Products)
group by StoreID;
但这会返回以下错误:
单行子查询返回多行
在数据方面,我想得到以下结果:
StoreID count(ProductID)
------- ----------------
1 2
2 4
这些商店的平均价格为:
StoreID avg(Price)
------- ----------
1 6.5
2 7.5
所有商店的平均价格为4.6。
你能帮我吗?预先感谢。
答案 0 :(得分:2)
您要表达:
select p.StoreID, count(*)
from Products
group by p.StoreId
having avg(Price) > (select avg(Price) from Products);
也就是说,您需要一个having
子句,而无需在StoreId
级别上重新聚合数据。
答案 1 :(得分:1)
您可以使用以下分析功能来实现此目的:
Select distinct storeid, store_avg from
(Select t.*,
Avg(price) over () as all_avg,
Avg(price) over (partition by storeid) as store_avg
From products)
Where store_avg > all_avg;
干杯!