根据值将数据分为多个范围

时间:2019-04-29 11:01:46

标签: sql sql-server tsql

我有一系列数据值。我想根据值将其分为多个范围,例如3个范围。例如:假设我的数据值看起来像这样

1669
2653
2662
2669
2701
2711
2748
2770
2821
2832
2848
2850
2855
2859
2868
2893
2908
2922
2939
2968
2992
3005
3025
3026
3031
3033
3034
3036
3053
3073
3087
3087
3099
3128
3128
3131
3133
3140
3174
3182
3182
3189
3204
3204
3214
3219
3224
3225
3236
3244
3272
3295
3295
3296
3299
3305
3305
3402

我的最终目标是能够从该集合中巧妙地确定低-中-高-意思是,我需要代码来找出哪个将具有2个良好的边界值-例如<2600,> = 2600到3000, > = 3000。像K-means聚类之类的...值的集合将始终更改,甚至可能在10或100s,而不是这里的1000s。

The attached image show the distribution of the data points across dates on the x axis. Visually it becomes clear how the data is distributed. I want to be able to do the same via SQL

SQL中的

NTILE分成相等的存储区,因此不符合我的要求。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我不知道我是否了解您想要的内容,但是如果要将一组数据划分为3组并找到每个组的范围,我认为以下内容将有助于使用NTILE。

首先,我将数据添加到内存表中进行测试,如下所示:-

declare @dataSet table ([value] int)
insert into @dataSet values 
(1669 ),(2653 ),(2662 ),(2669 ),(2701 ),(2711 ),(2748 ),(2770 ),(2821 ),(2832 ),(2848 ),(2850 ),(2855 ),
(2859 ),(2868 ),(2893 ),(2908 ),(2922 ),(2939 ),(2968 ),(2992 ),(3005 ),(3025 ),(3026 ),(3031 ),(3033 ),
(3034 ),(3036 ),(3053 ),(3073 ),(3087 ),(3087 ),(3099 ),(3128 ),(3128 ),(3131 ),(3133 ),(3140 ),(3174 ),
(3182 ),(3182 ),(3189 ),(3204 ),(3204 ),(3214 ),(3219 ),(3224 ),(3225 ),(3236 ),(3244 ),(3272 ),(3295 ),
(3295 ),(3296 ),(3299 ),(3305 ),(3305 ),(3402 )

然后将尝试获取范围。

    ;with cte as (
    select NTILE(3) over (order by [value]) [group],[value] from @dataSet
    )
    select [group],min([value]) [LowerRange],max([value]) [HigherRange] From cte group by [group]

分组是为了获得每个组的上限和下限

结果如下:-

group   LowerRange  HigherRange
=====   ==========  ==========
1       1669        2968
2       2992        3174
3       3182        3402

希望这会有所帮助。