liberty- 2015-08-12 02:24 采纳率: 50%
浏览 2926

SQL 根据表A的数据修改表B,当一条表B的数据匹配到多条表A的数据时选其中一条修改

 update B
set _flg = 'update',
b_string1 = t4.a_string1,
b_string2 = t4.a_string2,
b_string3 = t4.a_string3,
b_string4 = t4.a_string4,
b_string5 = t4.a_string5,
update_by = current_user,
update_date = getdate()
from B t3
inner join A t4 
on t3.id = t4.id and t3.no = t4.no
where exists
(
    select 1 from A t5 where t5.id + ',' +t5.no = t3.id + ',' + t3.no
    and (
            t3.b_string1 <> t5.a_string1
            or t3.b_string2 <> t5.a_string2
            or t3.b_string3 <> t5.a_string3
            or t3.b_string4 <> t5.a_string4
            or t3.b_string5 <> t5.a_string5
        )
)

当id 和 no 相同的情况下,A数据出现两条或者多条,怎么选择其中的一条来修改,代码应该怎么写? 求大神指点

  • 写回答

2条回答 默认 最新

  • danielinbiti 2015-08-12 02:37
    关注

    通过id和no组合分组,ROW_NUMBER()over (partition by id+','+no ) rn先对A表进行行编号,条件多加一个 rn=1

     update B
    set _flg = 'update',
    b_string1 = t4.a_string1,
    b_string2 = t4.a_string2,
    b_string3 = t4.a_string3,
    b_string4 = t4.a_string4,
    b_string5 = t4.a_string5,
    update_by = current_user,
    update_date = getdate()
    from B t3
    inner join (select a.*,ROW_NUMBER()over (partition by id+','+no ) rn from a)  t4 
    on t3.id = t4.id and t3.no = t4.no
    where exists
    (
        select 1 from A t5 where t5.id + ',' +t5.no = t3.id + ',' + t3.no
        and (
                t3.b_string1 <> t5.a_string1
                or t3.b_string2 <> t5.a_string2
                or t3.b_string3 <> t5.a_string3
                or t3.b_string4 <> t5.a_string4
                or t3.b_string5 <> t5.a_string5
            )
    ) and t4.rn=1
    没有建表语句和数据,SQL没有调测,只是这么一个意思。
    
    评论

报告相同问题?

悬赏问题

  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误