SQL非编号组的编号

时间:2018-04-13 01:49:49

标签: sql-server

任何人都可以帮我一个select语句,它会返回我在下面显示的“Section”编号吗?我发现了一些类似的问题和答案,但没有解决我的具体要求。

我的数据(本例简化)是“序列”和“数据”列,我想根据以下内容生成“部分”列:

  1. 我的数据按照“序列”列中的值进行排序,
  2. 基于数据列的中断值:
  3. enter image description here

    请注意,我想要的“部分”编号打破了数据列的“值的变化”,而不考虑该列中的实际值或它们必须采用任何特定的顺序。

    我还应该澄清一下,Sequence列中的值是连续的,因此序列中没有缺失的数字,所选择的答案满足。

2 个答案:

答案 0 :(得分:2)

我们可以在这里使用行号方法的差异:

{
    "type": "FeatureCollection",
    "features": [
        {
            "type": "Feature",
            "properties": {
                "name": "Test Drive for data ",
                "time": "2018-04-03T01:48:51Z",
                "coordTimes": [//ARRAY OF DATETIMES] },
            "geometry": {
                "type": "LineString",
                "coordinates": [ //ARRAY OF X, Y, and ELEVATION COORDINATES]    
                ]
            }
        }
    ]
}

enter image description here

Demo

很难用语言解释为什么这种方法在这里工作,但如果你很好奇,你可以尝试WITH cte AS ( SELECT *, ROW_NUMBER() OVER (ORDER BY Sequence) - ROW_NUMBER() OVER (PARTITION BY Data ORDER BY Sequence) rn FROM yourTable ) SELECT Sequence, Data, DENSE_RANK() OVER (ORDER BY rn) AS Section FROM cte ORDER BY Sequence; 看看发生了什么。

答案 1 :(得分:1)

此解决方案使用窗口函数两次。

-- [2] then use dense_rank() on the smallest sequence by Data
select  *, dense_rank() over(order by s)
from
(
    -- [1] find the smallest Sequence for each group of Data
    select  *, s = min(Sequence) over (partition by Data)
    from    tbl
) t
order by Sequence
相关问题