0

请帮助我使用可以将数据动态存储到范围中的 SQL Server 查询。

这是我的源数据:

价值
=======
45

33.5
33.1
33
32.8

25.3
25.2
25.1
25

21.3
21.2
21.1
20.9

12.3
12.2
12.15
12.1
12
11.8

预期输出:

价值排名
==============
45 1
(此范围内的平均值为 45)

33.5 2
33.1 2
33 2
32.8 2
(平均值为 33.1 - (-10%) 29.79 到 36.41 (+10%) 范围内的任何值都应为 2)

25.3 3
25.2 3
25.1 3
25 3

21.3 4
21.2 4
21.1 4
20.9 4

12.3 5
12.2 5
12.15 5
12.1 5
12 5
11.8 5

DENSE、RANK 和 NTILE 似乎没有给我这样的排名。该范围是动态的,之前不知道。任何帮助高度赞赏。

分桶规则为:

每个桶包含一个与平均值相差 10% 的数据集

4

2 回答 2

1

这是一种方法:

select val, dense_rank() over (order by cast(val/10 as int) desc) ntile 
from yourtable

使用但在子句dense_rank中指定您的存储桶。order by(我假设这就是它适用于您的示例数据的方式)

于 2017-01-09T07:13:24.337 回答
0

首先将该值转换为具有 2 位小数的数字。
然后,使用基于小数点后第一个数字CASE的执行FLOOR或函数表达式。 然后使用函数根据舍入值给出排名。ROUND
DENSE_RANK

询问

select z.[Value], dense_rank() over(order by z.[val_rounded] desc) as [Rank] from(
    select t.[Value],
    case when substring(t.[Value2], charindex('.', t.[Value2], 1) + 1, 1) > 5 
    then round(t.[Value], 0) else floor(t.[Value]) end as [val_rounded] from(
        select [Value], cast((cast([Value]as decimal(6, 2))) as varchar(50)) as [Value2]
        from [your_table_name]
    )t
)z;

Demo

于 2017-01-09T08:22:45.047 回答