PostgreSQL ntile() 分区

fab*_*vys 3 postgresql aggregate window-functions group-by

我有一个带有人口值的点网格。每个点都有一个 id 和人口值。我也有一个 state_id,它说明了要点是什么状态。

现在我想计算每个州的百分位数 ntile(100)。

   SELECT  id, population, state_id, 
   ntile(100) OVER(ORDER BY car20) as percentile
   FROM avi_threshold01 
Run Code Online (Sandbox Code Playgroud)

当我使用它时,我认为它会计算所有点和状态的 ntile。

ype*_*eᵀᴹ 6

如果你想要百分位数 per state,那么PARTITION BY state_idOVER子句中使用。

GROUP BY至少看起来是假的。我认为如果你想要百分位数,它需要被删除。反正分组PK是无操作的。

   SELECT  
       id, population, state_id, 
       ntile(100) OVER (PARTITION BY state_id ORDER BY car20) AS percentile
   FROM 
       avi_threshold01 ;
Run Code Online (Sandbox Code Playgroud)