删除分区中的重复项,同时保持行号的顺序
Remove duplicates in partition while maintaining order of row number
我有一个 table,如下所示,有多个条目和重复的 ID/SUBIDs。
Id subid Rownum
1 A 1
1 A 2
2 A 1
2 B 2
2 A 3
3 C 1
3 C 2
3 D 3
3 D 4
3 C 5
3 A 6
以上table按ID分区,行号基于每个分区的subids。
我想创建一个新的 table,其中任何分区中都没有重复的 ID/SUBID 组合,同时还保持 subids 的顺序。
输出
Id subid Rownum
1 A 1
2 A 1
2 B 2
3 C 1
3 D 2
3 A 3
你能帮我解决这个问题吗?如果您需要更多信息,请告诉我。
谢谢!
尝试以下操作。首先使用 distinct
获取 Id 和 subId,然后使用 window 函数 row_number
。这是 demo.
select
Id,
subid,
row_number() over (partition by Id order by subid) as rowNum
from
(
select
distinct Id,
subid
from myTable
) t
输出:
| Id | subid | rowNum |
| --- | ----- | ------- |
| 1 | A | 1 |
| 2 | A | 1 |
| 2 | B | 2 |
| 3 | A | 1 |
| 3 | C | 2 |
| 3 | D | 3 |
如果我没理解错的话,你想要:
select id, subid,
row_number() over (partition by id order by min(rownum)) as new_rownum
from t
group by id, subid
order by id, min(rownum);
这是一个聚合查询,它使用 min(rownum)
来维护您想要的顺序。
Here 是一个 db<>fiddle(恰好使用 Postgres,但这并不重要)。
我有一个 table,如下所示,有多个条目和重复的 ID/SUBIDs。
Id subid Rownum
1 A 1
1 A 2
2 A 1
2 B 2
2 A 3
3 C 1
3 C 2
3 D 3
3 D 4
3 C 5
3 A 6
以上table按ID分区,行号基于每个分区的subids。
我想创建一个新的 table,其中任何分区中都没有重复的 ID/SUBID 组合,同时还保持 subids 的顺序。
输出
Id subid Rownum
1 A 1
2 A 1
2 B 2
3 C 1
3 D 2
3 A 3
你能帮我解决这个问题吗?如果您需要更多信息,请告诉我。
谢谢!
尝试以下操作。首先使用 distinct
获取 Id 和 subId,然后使用 window 函数 row_number
。这是 demo.
select
Id,
subid,
row_number() over (partition by Id order by subid) as rowNum
from
(
select
distinct Id,
subid
from myTable
) t
输出:
| Id | subid | rowNum |
| --- | ----- | ------- |
| 1 | A | 1 |
| 2 | A | 1 |
| 2 | B | 2 |
| 3 | A | 1 |
| 3 | C | 2 |
| 3 | D | 3 |
如果我没理解错的话,你想要:
select id, subid,
row_number() over (partition by id order by min(rownum)) as new_rownum
from t
group by id, subid
order by id, min(rownum);
这是一个聚合查询,它使用 min(rownum)
来维护您想要的顺序。
Here 是一个 db<>fiddle(恰好使用 Postgres,但这并不重要)。