【发布时间】:2021-02-28 21:39:08
【问题描述】:
我有一组这样的值:
40
50
50
66
83
100
100
100
100
100
100
100
100
100
100
100
100
当我在 excel 中执行四分位数函数时,我得到了第一个四分位数 (25)、第二个四分位数 (50)、第三个四分位数 (75) 和最大值 (100) 的这四个值
四分位数 = 83.33, 100, 100, 100
所以当我比较一个获得 80% 的销售代表时,根据 excel 计算,他们将落在最后四分之一。
我需要在 sql 中重做相同的功能,并在下面给出了我的代码。
declare @sales table(
salesRepId int,
percentageSales int)
insert into @sales(salesRepId, percentageSales)
values(1,40)
,(2,50)
,(3,50)
,(4,66.7)
,(5,83.33)
,(6,100)
,(7,100)
,(8,100)
,(9,100)
,(10,100)
,(11,100)
,(12,100)
,(13,100)
,(14,100)
,(15,100)
,(16,100)
,(17,100);
with quintile as(
select percentagesales, ntile(4) over(order by percentagesales)
as quintile
from (select distinct percentagesales from @sales) as s
)
select salesrepid, r.percentagesales, q.quintile
from @sales r
join quintile q on r.percentagesales = q.percentagesales
order by q.quintile, percentagesales
当我运行它时,我得到以下结果集: Query results
salesrepid percentagesales quintile
1 40 1
2 50 1
3 50 1
4 66 2
5 83 3
6 100 4
7 100 4
8 100 4
9 100 4
10 100 4
11 100 4
12 100 4
13 100 4
14 100 4
15 100 4
16 100 4
17 100 4
根据sql,80%会落在中间四分位。
SQL查询中如何获取类似于excel的四个百分位数
【问题讨论】:
-
你能举个例子吗
-
Examples...
-
我试过了,我已经接近但得到了低四分位数或 q1 83,应该是 83.33 我错过了什么?基本上我的查询应该返回与其他销售代表百分比相比,四分位用户将在网页中反映
标签: sql-server quartile