sql - 如何为具有不同键的一组记录生成唯一标识符?
问题描述
我有一个如下所示的记录集:
| key_sk | unique_id |
|--------|--------------------------------------|
| 2 | null |
| 2 | null |
| 3 | 83a1c90b-e58d-4db4-b438-a79edfb28e60 |
| 3 | 83a1c90b-e58d-4db4-b438-a79edfb28e60 |
| 4 | 4ce66783-0b84-4e8a-a0de-c3284e4d9cd0 |
| 5 | null |
我想为每个为空的唯一key_sk
集生成一个唯一ID。unique_id
对于上述内容,我想要key_sk 2
一个unique_id
喜欢key_sk 3
的。
uniqueidentifier
我在下面的尝试为每组产生了不同的结果。我认为这是因为公用表表达式的递归性质:每次加入 CTE 都会导致NEWID()
被调用。
;with update_id_cte as
(
select distinct hr.key_sk
,NEWID() as gened_unique_id
from history_record hr
where hr.unique_id is null
)
update hr
set hr.unique_id = cte.gened_unique_id
from history_record hr
join update_id_cte cte
on hr.key_sk = cte.key_sk
可能有比使用 CTE 更简单的方法来执行此操作。如何为每个 distinct生成和更新history_record
表?uniqueidentifier
key_sk
解决方案
而不是select distinct
,您可以使用group by
:
with update_id_cte as (
select hr.key_sk, NEWID() as gened_unique_id
from history_record hr
where hr.unique_id is null
group by hr.key_sk
)
update hr
set hr.unique_id = cte.gened_unique_id
from history_record hr join
update_id_cte cte
on hr.key_sk = cte.key_sk;
如果某些key_sk
值可能同时具有键NULL
和非NULL
键并且您想保留现有值,则可以调整逻辑:
with update_id_cte as (
select hr.key_sk, coalesce(max(hr.unique_id), NEWID()) as gened_unique_id
from history_record hr
group by hr.key_sk
)
update hr
set hr.unique_id = cte.gened_unique_id
from history_record hr join
update_id_cte cte
on hr.key_sk = cte.key_sk
where hr.unique_id is null;
推荐阅读
- reactjs - 函数使用 this.state 并将其传递给另一个组件
- firebase - Firebase 预览频道是否使用相同的数据库?
- rest - ASP.NET Core 5 路由重定向
- unix - CURL 无法连接到链接
- python - 在 python-sklearn 中出现“ValueError: Expected 2D array, got 1D array”错误
- python - 带有 .after() 语句的程序中未显示 TKinter 窗口
- python - 在python中使用列表作为函数参数
- ssl - 用于 TLS/SSL 和身份(签名)的证书之间有区别吗?
- angular - 使用 datefns 的当年星期的下拉列表
- python - 使用 Pymongo 到 MongoDB 实例的多个连接