sql - 在插入新行时结转列值
问题描述
我有一个SQL Server
包含以下列的表格:
Item Eng1 Eng2 Eng3 UpdatedDate UpdatedBy
表中的当前条目是:
item1 jacob john null 1/1/2000 Sheila123@gmail.com
item2 alex null null 2/1/2000 clint123@gmail.com
现在,假设item1
要在其中插入另一个条目Eng2=greg
,Eng3=tom
因此Eng1=jacob
必须结转。因此条目现在应该是:
item1 jacob john null 1/1/2000 Sheila123@gmail.com
item2 alex null null 2/1/2000 clint123@gmail.com
item1 jacob greg tom 2/10/2000 sally123@gmail.com
因此,如果与新数据条目不同,则基本上替换列值,否则将继续存在的最新列值
解决方案
您可以找到前 1 个匹配项,并插入新记录以替换现有记录的空值。
于 2020 年 9 月 22 日更新。包括全新记录的插入
declare @eng1 varchar(255),
@eng2 varchar(255) = 'greg',
@eng3 varchar(255) = 'tom',
@item varchar(255) = 'item1',
@updatedDate date = '2/10/2000',
@updatedBy varchar(255) = 'sally123@gmail.com'
Insert into yourTable (Item, Eng1, Eng2, Eng3, UpdatedDate, UpdatedBy)
select top 1 Item,
isnull(@eng1, Eng1),
isnull(@eng2, Eng2) ,
isnull(@eng3, Eng3),
UpdatedDate = @updatedDate,
@updatedBy
from yourTable
where Item = @item
Union
Select @item,
@eng1,
@eng2,
@eng3,
UpdatedDate = @updatedDate,
@updatedBy
From yourTable
where not exists (Select 1 From yourTable where Item = @item) --For entirely new records
order by UpdatedDate desc
推荐阅读
- ios - 尽管用户在那里,但 Firebase Auth 不打印用户登录
- linux - 使用 GHC 的共享库
- sql - 将时间戳舍入到 30 分钟间隔以进行分组
- json - readyState 3 之前的响应输出
- compare - Tableau - 需要将过去 7 天的记录数与过去 7 天的记录数进行比较 -1
- kubernetes - 哪个隔离 Kubernetes 集群用于生产环境?
- javascript - 反转多维数组
- selenium-webdriver - 如何使用伊斯坦布尔为基于 selenium+java 的框架设置代码覆盖率
- spring-boot - Spring Security - 用于执行器端点的自定义身份验证提供程序和 HTTP 基础
- javascript - Coderbyte 挑战:问号