[英]How to apply NTILE(4) using range of column values?
想用NTILE
查看各國的森林分布占土地總面積的百分比。 我想使用的列中的值范圍是從 0.00053 到非常接近 98.25,並且國家在該范圍所暗示的四分位數中分布不均勻,即 0 到 25、25 到 50、50 到 75,以及大約 75 到 100。 相反, NTILE
只是將表分成具有相同行數的四組。 如何使用NTILE
根據值分配分位數?
SELECT country, forest, pcnt_forest,
NTILE(4) OVER(ORDER BY pcnt_forest) AS quartile
FROM percent_forest
WIDTH_BUCKET function 非常適合這種情況:
WIDTH_BUCKET(Oracle)允許您構造等寬直方圖,其中直方圖范圍被划分為具有相同大小的區間。 (將此 function 與創建等高直方圖的 NTILE 進行比較。)
它受 Oracle、雪花、PostgreSQL、...
你的代碼:
SELECT country, pcnt_forest
,WIDTH_BUCKET(pcnt_forest, 0, 1, 4) AS w
,NTILE(4) OVER(ORDER BY pcnt_forest) AS ntile -- for comparison
FROM percent_forest
ORDER BY w
Output:
+----------+--------------+----+-------+
| COUNTRY | PCNT_FOREST | W | NTILE |
+----------+--------------+----+-------+
| A | .05 | 1 | 1 |
| B | .06 | 1 | 1 |
| C | .07 | 1 | 2 |
| E | .49 | 2 | 2 |
| D | .51 | 3 | 3 |
| F | .96 | 4 | 3 |
| G | .97 | 4 | 4 |
| H | .98 | 4 | 4 |
+----------+--------------+----+-------+
您可以使用case
表達式:
select pf.*,
(case when pcnt_forest < 0.25 then 1
when pcnt_forest < 0.50 then 2
when pcnt_forest < 0.75 then 3
else 4
end) as bin
from percent_forest pf;
或者,更簡單,使用算術:
select pf.*,
floor(pcnt_forest * 4) + 1 bin
from percent_forest pf;
我不會在本專欄中使用“四分位數”一詞。 四分位數意味着四個大小相等的箱(或至少在給定重復值的情況下盡可能接近)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.