[英]How do I find the average of the result of a group by SQL query?
因此,假設我從一個名為 Inventory 的表開始,如下所示,其中每個非唯一存儲 ID 有多個唯一項目:
物品編號 | 存儲 ID |
---|---|
453 | 100 |
234 | 100 |
642 | 150 |
234 | 200 |
343 | 200 |
143 | 200 |
我根據其存儲 ID 對項目進行分組,因此它會產生下表 - ( select itemID, storageID from Inventory group by storageID
)
物品編號 | 存儲 ID |
---|---|
453, 234 | 100 |
642 | 150 |
234、343、143 | 200 |
但接下來是我堅持的部分:我想返回一個數字結果,表示每個存儲的平均項目數。 因此,這將涉及計算每個不同存儲的項目數(即: storageID 100 有 2 個項目, storageID 200 有 3 個項目),然后找到平均值。 因此,在我分享的示例中,平均值為 (2+1+3)/3 = 2.67 件/存儲。 我該如何查詢 MySQL 呢? 我什至需要使用 group by 作為開始嗎?
對您的數據進行分組並在每個組上使用count()
。
select avg(cnt)
from
(
select count(*) as cnt, storageID
from Inventory
group by storageID
) tmp
您可以按如下方式使用group by
:
select avg(cnt) as average_
(select count(*) as cnt
from your_table t
group by storageid) t
您不需要子查詢:
select count(*) / count(distinct storageID) as avg_per_storageID
from Inventory ;
平均值是項目總數除以storageID
的數量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.