选择X距离最远的数值

时间:2019-07-08 23:39:37

标签: sql sql-server

如何从按数字排序的数字池中选择X个数字,以使每个结果的值与每个其他数字的距离尽可能远。

例如,给定:

1
2
3
4
5
6
7
8
9

对于X = 3,它可能返回:1、5、9

对于X = 5,它可能返回:1,3,5,7,9

2 个答案:

答案 0 :(得分:2)

这可能是答案。只需更改@x@t

@x是您想要的数字计数

@t是您集合中后续数字的计数

declare @x int = 5
declare @t int = 9
;with ct as (
    -- this section is just for generating sequence numbers
    select top (@t) N = ROW_NUMBER() over (order by object_id)
    from sys.tables
)
select N
from ct 
where N % ((@t / @x) + 1) = 1 or N = 1

示例示例结果

enter image description here

enter image description here

答案 1 :(得分:0)

您需要第一个和最后一个值,然后是中间的值。就像这样:

select t.*
from (select t.*, row_number() over (order by n) as seqnum,
             count(*) over () as cnt
      from t
     ) t
where seqnum = 1 or seqnum = cnt or
      seqnum % (cnt / nullif((@x - 1, 0))) = 1;