简体   繁体   English

SQL Increment值取决于其他列中的更改

[英]SQL Increment value depending on changes in other columns

Similar to this : T-SQL incrementing counter based on change in a column value 与此类似: T-SQL基于列值的变化递增计数器

I have this table : 我有这张桌子:

ID  |  VALUE
5   |  A    
6   |  A    
6   |  A    
6   |  B    
6   |  A    
6   |  B    
6   |  B    
6   |  A    
6   |  C    

The desired result is to have this : 期望的结果是:

ID  |  VALUE    | GROUP
5   |  A        | 1
6   |  A        | 2
6   |  A        | 2
6   |  B        | 3
6   |  A        | 4
6   |  B        | 4
6   |  B        | 4
6   |  A        | 5
6   |  C        | 6

A new column (GROUP) with a value that increments everytime the first two columns change, but doesn't increment when the first two columns values are the same as the previous line. 一个新列(GROUP),其值在前两列每次更改时递增,但在前两列值与上一行相同时不会递增。

So far, with the RANK OVER() function, the best I can achieve is this : 到目前为止,使用RANK OVER()函数,我能达到的最好效果是:

ID  |  VALUE    | GROUP
5   |  A        | 1
6   |  A        | 2
6   |  A        | 2
6   |  B        | 3
6   |  A        | 2
6   |  B        | 3
6   |  B        | 3
6   |  A        | 1
6   |  C        | 4

Let me assume that you have a column called ordering that specifies the ordering of the records. 我假设您有一个名为ordering的列,它指定记录的顺序。 SQL tables represent unordered sets, so there is no "natural" ordering to the rows. SQL表表示无序集,因此行没有“自然”排序。

You can do what you want with a difference of row numbers and then some additional manipulation: 您可以使用行号的差异然后进行一些额外的操作来执行您想要的操作:

select id, value, dense_rank() over (order by grp) as grouping
from (select t.*,
             min(ordering) over (partition by id, value, seqnum - seqnum_iv) as grp
      from (select t.*,
                   row_number() over (order by ordering) as seqnum,
                   row_number() over (partition by id, value order by ordering) as seqnum_iv
            from t
           ) t
     ) t;

The innermost subquery calculates to sequences of values. 最里面的子查询计算值序列。 I encourage you to look at the results to see what is happening. 我鼓励你看看结果,看看发生了什么。 The difference is constant for each of your "islands". 每个“岛屿”的差异都是不变的。

The second gets the minimum of the ordering value for each group. 第二个获得每个组的最小ordering值。 This can then be used to assign a sequential value as the ultimate result. 然后,可以使用它将顺序值指定为最终结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM