我正在使用SQL Server。
我有一个数据库表,其中包含一些用户数据,如下所示:
ID UNIT VAL1 VAL2 MAT1 MAT2 LVL_CODE
BB123456789 FALSE 1 1 ROL M NULL
AA004000000 FALSE 40 1 ROL PAL 8
AA004000000 FALSE 1 72 ROL CV
AA004000000 FALSE 20 1 ROL M 6
在该表中,存在具有相同ID的记录,例如:AA004000000具有三个记录。而ID BB123456789只有一个记录。
我想为满足以下条件的记录设置UNIT=TRUE,VAL1=1,VAL2=1:
情况1:如果VAL1=VAL2,则更新UNIT=TRUE、VAL1=1、VAL2=1。如果有多个具有相同ID的记录满足情况1或VAL1!=VAL2,则我们需要考虑情况2。
情况2:如果MAT1=MAT2,则更新UNIT=TRUE、VAL1=1、VAL2=1。如果有多个具有相同ID的记录满足情况2或MAT1!=MAT2然后考虑情况3。
情况3:对于LVL_CODE最低的ID,更新UNIT=TRUE,VAL1=1,VAL2=1。由于我们有多个具有相同ID的记录,我们只需要将一个记录更新为TRUE例如:ID:AA004000000有3条记录,因为我只需要为LVL_CODE为Least的一条记录设置UNIT=TRUE。AA004000000的最小LVL_CODE为6。
因此,期望的结果应该是:
ID UNIT VAL1 VAL2 MAT1 MAT2 LVL_CODE
BB123456789 TRUE 1 1 ROL M NULL
AA004000000 FALSE 40 1 ROL PAL 8
AA004000000 FALSE 1 72 ROL CV
AA004000000 TRUE 1 1 ROL M 6
有人能帮我找出这些记录并更新吗?
在存储过程中尝试此操作,当然会对进行一些更改
if (select COUNT * from [yourTable] where val1=val2) =1
begin
declare @id =scope_identity();
update [yourTable] set -- -- your values unite true and val1=val2=1
end
else if(select COUNT * from [yourTable] where val1=val2) >1 or exists (select COUNT * from
[yourTable] where val1!=val2)
begin
if (select COUNT * from [yourTable] where mat1=mat2) =1
begin
declare @id =scope_identity();
update [yourTable] set -- your values unite true and val1=val2=1
end
else
if(select COUNT * from [yourTable] where mat1=mat2) >1 or exists (select COUNT * from
[yourTable] where mat1!=mat2)
begin
declare @id =scope_identity();
update [yourTable] set -- your values unite true and val1=val2=1
end
end