sql - 在 SQL 中标记百分位数

标签 sql sql-server percentile

我想在 SQL 中创建一个类似于下面的 flag 的列,我可以在其中识别给定时间段内每个 block 组销售额的前 20% 和后 20%。我已经将销售额汇总到 block 组,但现在我无法标记它们。例如,在 bg2010 1 中,有 215 笔销售额大约占该时间段内所有销售额的前 20%(实际上是 21.5%,但这没关系)。

我试过 percentile_cont 命令,但似乎不是我要找的东西,但这也可能是因为我不完全理解它,所以任何帮助将不胜感激!

bg2010  sales16_17   flag
   1    215          top 20th 
   2    150 
   3    115 
   4    100 
   5    95  
   6    95  
   7    85  
   8    65           bottom 20th
   9    45           bottom 20th
   10   35           bottom 20th

最佳答案

使用 ntile() 获取从 1 到 5 的数字

select t.*, ntile(5) over (order by sales16_17 desc) as tile

如果你想把它作为一个标志,你可以这样做:

select t.*,
       (case ntile(5) over (order by sales16_17 desc)
            when 1 then 'top 20%'
            when 5 then 'bottom 20%'
        end) as flag

关于sql - 在 SQL 中标记百分位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51483288/

相关文章:

.net - 为什么 SqlConnection 在交易中途关闭?

python - Pandas - 基于每列的前 x% 值,标记为新数字

mySQL 选择去年每个月有交易的任何部门

使用分组依据和按日期排序的 SQL 选择

mysql - 查找具有可互换行的相似条目

sql - 获取表中下一行的值总和

sql - SQL Server 上的 INSERT OR UPDATE 解决方案

sql-server - SQL Server 2008 R2 上的插入和选择性能

python-2.7 - pandas.DataFrame.describe() 与 numpy.percentile() NaN 处理

python - 当 inf 存在时, np.percentile 返回与 np.median 不同的中位数