我想在 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/