簡體   English   中英

將唯一的組 ID 分配給由其他值分隔的具有相同列值的行集

[英]Assign Unique Group Id To Sets of Rows with Same Column Value Separated by Other value

我有一些看起來像這樣的數據:

uid radius
1   10
2   10
3   10
4   2
5   4
6   10
7   10
8   10

我想要的是每個具有相同半徑值的組都有自己的唯一 id,例如:

uid radius GroupdId
1   10     1
2   10     1
3   10     1
4   2      2
5   4      3
6   10     4
7   10     4
8   10     4

我不希望半徑為 10 的第二組與第一組具有相同的 groupid(不是 1)。

我正在使用 SQL Server,但解決方案在所有數據庫中都應該相同。

(我以前這樣做過,但對於我的一生,我不記得我是怎么做到的。)

嘗試這個:

with t as
(
    select
        uid,
        radius,
        lag(radius,1) over (order by uid) as prev_rad
    from
        radtable
)

select
    uid,
    radius,
    sum
    (
        case when radius = coalesce(prev_rad,radius) then 0 else 1 end
    )  
    over 
    (
        order by uid
    ) + 1 as GroupID
from 
    t

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM