用SQL Server中表2上的键替换数据
我的问题是用SQL Server中的密钥替换。有人能给我一个疑问来做这件事吗 谢谢你的回答用SQL Server中表2上的键替换数据,sql,sql-server,Sql,Sql Server,我的问题是用SQL Server中的密钥替换。有人能给我一个疑问来做这件事吗 谢谢你的回答 表1: ID | Code | Des | more columns ---+------+-----+------------- 1 | 100 | a | ... 2 | 200 | b | ... 3 | 300 |data3| ... 表2: ID | Code | Des ---+------+------
表1
:
ID | Code | Des | more columns
---+------+-----+-------------
1 | 100 | a | ...
2 | 200 | b | ...
3 | 300 |data3| ...
表2
:
ID | Code | Des
---+------+------
1 | 100 | data1
2 | 200 | data2
结果必须是:
ID | Code | Des | more columns
---+------+-----+-------------
1 | 100 |data1| ...
2 | 200 |data2| ...
3 | 300 |data3| ...
使用JOIN
查询
SELECT t1.ID, t1.Code,
CASE WHEN t1.Des LIKE 'data%' THEN t1.Des ELSE t2.Des END AS Des
FROM Table1 t1
LEFT JOIN Table2 t2
ON t1.ID = t2.ID;
执行
左连接
,如果没有table2.Des值,则改为table1.Des:
select t1.ID, t1.Code, coalesce(t2.Des, t1.Des), t1.more Column
from table1 t1
left join table2 t2 on t1.code = t2.code
或者,也许你想要这个:
select * from table2
union all
select * from table1 t1
where not exists (select 1 from table2 t2
where t2.code = t1.code)
也就是说,返回表2行,如果代码在表1中,但不在表2中,也返回该行。好的,那么您希望表1中的所有结果,但在表2中可用时使用“Des”中的值?你会想做这样的事情
SELECT a.ID
,b.Code
,ISNULL(b.Des,a.Des) AS Des
FROM Table1 a
LEFT JOIN Table2 b ON a.ID = b.ID
试试这个:
SELECT Table1.ID,
Table1.Code,
ISNULL(Table2.Des, Table2.Des) AS Des
FROM Table1
LEFT OUTER JOIN Table2
ON Table1.Code = Table2.Code;
您说过“如果代码在2表中是公共的”,那么就在代码上而不是在ID上进行连接提示:
内部连接
。您不清楚想要什么。结果中的“Des”列是否应在第二个表中报告相应的值?@RobertKock如果表2中的代码通用,Des的值来自表2,但如果表2中的代码不通用,Des的值来自表1Add ID=4到表2中,并且具有不同的代码值。(或者代码是连接列?@jarlh yea表2是一种重组表,表2中的描述必须替换为表1中的描述,其中t1.code=t2.code应该是coalesce(t2.Des,t1.Des)
而不是coalesce(t2.Des,t2.Des)
@hadi.k,很好奇,你选择了哪一个?