代码之家  ›  专栏  ›  技术社区  ›  steve201

如何使用子序列列对列序列值重新编号

  •  0
  • steve201  · 技术社区  · 8 年前

    我有一个包含StructureNumber和SubStructureNumber列的表。StructureNumber按顺序编号,每个PropertyId从1开始。

    结构可以存在子结构,在这种情况下,SubStructureNumber将为>0,与父(顶级)结构具有相同的StructureNumber。

    顶级结构的子结构编号为0,而子结构(顶级结构的子结构)从1开始依次编号。

    示例数据:

    PropertyId | StructureNumber | SubStructureNumber
    144        | 1               | 0
    144        | 2               | 0
    197        | 1               | 0
    197        | 2               | 0
    197        | 3               | 0
    197        | 3               | 1
    197        | 3               | 2
    

    当属性的结构被删除时,挑战就来了。例如,如果删除了PropertyId 197的StructureNumber 2,我需要对该属性的结构重新编号以填充缺少的数字。

    PropertyId | StructureNumber | SubStructureNumber
    197        | 1               | 0
    197        | 3               | 0
    197        | 3               | 1
    197        | 3               | 2
    

    同样,如果删除了子结构,我需要为每个StructureNumber重新编号SubstructureNumber:

    PropertyId | StructureNumber | SubStructureNumber
    197        | 1               | 0
    197        | 3               | 0
    197        | 3               | 2
    

    我知道如何使用CTE对StructureNumber进行重新编号,如中所示 this post ,使用类似以下内容:

    DECLARE @PropertyId int = 197;
    WITH Renumber AS
    (
    SELECT
        StructureNumber, 
        ROW_NUMBER() OVER (ORDER BY os.StructureNumber DESC, 
            os.SubStructureNumber DESC) as StructureNumberNew
        FROM dbo.parcel_OtherStructures os
        WHERE os.PropertyId = @PropertyId
        ORDER BY os.StructureNumber DESC, os.SubStructureNumber DESC
    )
    UPDATE Renumber SET StructureNumber = StructureNumberNew;
    

    我只是不知道如何为每个StructureNumber重新编号,而不为这些行的StructureNumber增加ROW\u NUMBER()值。

    我看到有人提到使用DENSE\u RANK,但我不知道如何使用它来完成我的任务。

    1 回复  |  直到 8 年前
        1
  •  0
  •   uzi    8 年前

    尝试此查询。我想这就是你要找的

    select 
        *, dense_rank() over (partition by PropertyId order by StructureNumber) as StructureNumber
        , row_number() over (partition by PropertyId, StructureNumber order by SubStructureNumber) - 1 as SubStructureNumber
    from 
        myTable