sql - 将表与 SQL Server 2012 中的 sql/tsql 进行比较
问题描述
我在 SQL Server 2012 中有四个表:table1, table2, table3
和一个(结果/输出表)table4
table1
每天都会被截断并加载新数据。table1
columnscol1, col2, col3
类似于table2
columnscol7, col18, col9
和table3
columnscol9, col11, col7
,所以我们可以加载匹配行来回table2
和table3
问题
循环 table1 以检查每一行 (col1,col2,col3) 是否匹配 table2 中的任何行 (col7,col18,col9) 然后在 table4 中添加包含信息 table1.col1,table1.col2,table1.col3,table2.col6 的行, table3.col1,table3.col7 和一列指示其更新
如果 table1 中的行 (col1,col2,col3) 在 table2 中不存在,则在 table4 中添加包含信息 table1.col1,table1.col2,table1.col3,table2.col6,table3.col1,table3.col7 和一列来指示它是一个补充
如果 table2 中的行 (col7,col18,col9) 在 table1 中不存在,则在 table4 中添加包含信息 table1.col1,table1.col2,table1.col3,table2.col6,table3.col1,table3.col7 和一列来指示它是一个删除
返回 table4 作为结果
我们如何仅使用 SQL/TSQL 来做到这一点?
解决方案
本质上,您正在寻找子句full join
中的条件逻辑:from
insert into table4
select
t1.col1,
t1.col2,
t1.col3,
t2.col6,
t3.col1,
t3.col7,
case
when t2.col7 is null then 'insert'
when t1.col1 is null then 'delete'
else 'update'
end action
from table1 t1
full join table2 t2 on t1.col1 = t2.col7 and t1.col2 = t2.col8 and t1.col3 = t2.col9
full join table3 t3 on t1.col1 = t3.col9 and t1.col2 = t2.col11 and t1.col3 = t3.col7
目前还不清楚,你想用table3
. 可能,您想要left join
它而不是full join
,并检查前面两个表的条件,例如:
left join table t3
on t3.col9 = coalesce(t1.col1, t2.col7)
and t3.col11 = coalesce(t1.col2, t2.col8)
and t3.col7 = coalesce(t1.col3, t2.col9)
推荐阅读
- typescript - 为什么 isElementPresent() 在我的量角器脚本中不起作用?
- vuejs2 - 如何显示两个相邻的 v-navigation-drawer 并能够从左侧隐藏右侧?
- intellij-idea - 如何在 Intellij 插件中持久/回读运行配置参数
- c# - SQLite 在重建时删除参考
- sql - 合并具有相同值的行的日期范围
- java - 奇怪的安卓异常
- javascript - 如何从 Firebase 获取数据以创建列表?
- ruby - 复选标记字符 = "\u2713" - 打印输出不一致
- python - 替换 Excel 表格中的数据并保存表格
- java - 如何在 Java 中向 GridLayout 添加多个 TextView?