sql - 如何更新记录属于同一分区 SQL Server
问题描述
我在包含以下数据的数据库中有一个表:
GroupId ExceptionId ParentExceptionId row
1 101 NULL 1
1 102 NULL 2
1 103 NULL 3
2 104 NULL 1
2 105 NULL 2
2 106 NULL 3
3 107 NULL 1
3 108 NULL 2`
我写了一个以下查询来获取上面的行号:
with CTE_RN as
(
SELECT a.[GroupId], a.[SolId], a.[id],ParentExceptionId,
ROW_NUMBER() OVER(PARTITION BY a.[GroupId] ORDER BY a.[GroupId]) AS [row]
FROM [dbo].[trn_Report6_Zone1_Exception] a)
select * from cte_rn`
预期输出:使用具有相同组 ID 的第一条记录进行
更新ParentExceptionId
,并保持该第一条记录为空。ExceptionId
ParentExceptionId
GroupId ExceptionId ParentExceptionId row
1 101 NULL 1
1 102 101 2
1 103 101 3
2 104 Null 1
2 105 104 2
2 106 104 3
3 107 NULL 1
3 108 107 2`
解决方案
您可以使用first_value函数:
select GroupId, ExceptionId,
(case when f_value <> ExceptionId then f_value end) as ParentExceptionId, row
from (select *, first_value(ExceptionId) over (partition by GroupId order by ExceptionId) f_value
from [dbo].[trn_Report6_Zone1_Exception] a
) a;
以同样的方式,您可以使用updateable
cte :
with a as (
select *, first_value(ExceptionId) over (partition by GroupId order by ExceptionId) f_value
from [dbo].[trn_Report6_Zone1_Exception] a
)
update a
set ParentExceptionId = f_value
where f_value <> ExceptionId;
推荐阅读
- r - 组合 >100 个 xlsx 文件,由于文件中的列不同,POSIX 日期格式出现问题
- javascript - 如何在数组中传递文件名,然后在 cypress 中迭代文件上传功能
- json - JSON Schema - 设置静态名称
- html - 下拉不同大小问题html css调查表
- r - 有没有办法在 r 中的 ggplot 中向几何线添加标准误差线?
- javascript - 传单地图的第二个标签?
- c - C: 为什么我不能在函数内部 malloc
- jsf - 回发后为 p:media 加载 StreamedContent 会引发 java.io.FileNotFoundException
- c# - 从.NET调用WCF服务时如何以编程方式添加soap标头?
- swift - URL 构造函数在 Swift 中返回 `nil`