如何比较两个表并将空值替换为SQL Server / Azure SQL中其他表的值

时间:2019-04-22 07:18:04

标签: sql-server azure-sql-database

我有两个结构相同但值略有不同的表。如果表1的记录的某些列值为null,则必须更新为表2的值,反之亦然。

表1

+--------------------+
|  id | exp | last   |
+--------------------+
| 1  | null | 4005   |
| 2  | null | null   |
| 3  | 10/19  | 1001 |
+--------------------+

表2

+-------------------+
|  id | exp | last  |
+-------------------+
| 1  | 08/23 | null |
| 2  | 07/21 | 3867 |
| 3  | null  | 1001 |
+-------------------+

必需的输出

表3

+--------------------+
|  id | code | last  |
+--------------------+
| 1  | 08/23 | 4005  |
| 2  | 07/21 | 3867  |
| 3  | 10/19  | 1001 |
+--------------------+

这是外部联接吗?如果是的话,如何在SQL Server / Azure SQL上执行此操作?

3 个答案:

答案 0 :(得分:1)

select t1.id,
case when t1.exp is null then concat(t1.exp, t2.exp)  when t2.exp is null then concat(t1.exp, t2.exp) 
when t1.exp is not null then (t1.exp) when t2.exp is not null then (t2.exp)  end as exp,
case when t1.last is null then concat(t1.last, t2.last) 
when t2.last is null then concat(t1.last, t2.last) when t1.last is not null then (t1.last) 
when t2.last is not null then (t2.last) end as last
from Table1 t1 join Table2 t2 on t1.id=t2.id

enter image description here

答案 1 :(得分:0)

使用CASE或IIF的简单更新语句即可:

values_of_col_8 = df.col["name_col_8"].values
np.mean(values_of_col_8)

答案 2 :(得分:0)

使用coalesce()

select 
  t1.id,
  coalesce(t1.exp, t2.exp) exp,
  coalesce(t1.last, t2.last) last,
from table1 t1 inner join table2 t2
on t2.id = t1.id

如果table1值不是null,则优先使用left join值。
另外,如果2个表中的行数不相同,则应使用表中的table3,其中行数最多。
如果要将这些行插入insert into table3 (id, exp, last) select t1.id, coalesce(t1.exp, t2.exp) exp, coalesce(t1.last, t2.last) last, from table1 t1 inner join table2 t2 on t2.id = t1.id

User