[英]SQL Server - How calculate # of entities to hit 80% of sum total?
我列出了公司,他們的行業以及他們的年收入。
我需要按行業對列表進行分類,並找出每個行業中有多少家公司占該行業總收入的80%。
我可以運行該分區,可以確定每個行業的收入的80%,但是我不知道如何確定要達到80%的公司數量。 我唯一的想法是為每個行業列出一份清單,將收入從高到低排序,然后進行總結,直到達到80%的水平。
有內置的功能或巧妙的方法可以在這里為我提供幫助嗎?
謝謝!
我將使用窗口函數:
select industry, count(*)
from (select t.*,
sum(revenue) over (partition by industry order by revenue desc) as running_revenue,
sum(revenue) over (partition by industry) as total_revenue
from t
) t
where running_revenue - revenue < 0.8 * total_revenue
group by industry;
where
包括所有通過第一個通過80%閾值的公司。
可以使用其他功能,例如ntile()
和percentile()
。 我發現使用sum()
直接進行計算是最簡單的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.