我在不同的数据库(使用SQL 2012),Table1和Table2下有2个表,需要根据ID和Table2的值更新Table1
表1:
ID Seen-Date Disease-Cat
111 01/01/2008 value1
111 01/01/2010 value2
111 03/-5/2-11 value10
222 03/02/2015 value3
表2:
ID Registered-Date Main-Category Sub-category
111 01/01/2011 1:Blood Pressure 1.1 Blood Pressure Subcat
111 12/12/2011 1:Blood Pressure 1.2 Blood Pressure Subcat
333 02/02/2015 2:CardioVasular Disease 2.3 CardioVasular Disease Subcat
222 12/04/2013 3:Lung Disease 3.1 Lung Disease
444 01/01/2008 4:Electro cardiogram NULL
期望的输出:
ID Seen Date Value
111 01/01/2008 1.1 BP Subcat
111 01/01/2010 1.1 BP Subcat
111 03/-5/2-11 1.1 BP Subcat
444 03/02/2015 4 ECG
条件:
例如:
Table1(Disease Cat) Table2(Main Category & Sub Category codes)
1 BP 1:Blood Pressure
1.1 BP 1.1 Blood Pressure Subcat
当ID匹配时,使用table2的'Sub Category'值更新Table1的'Disease Cat'字段,如果'Sub category'为NULL,则使用Table2的'Main Category'字段更新Table1的'Disease Cat'。< / p>
当我运行以下脚本时,它会收到错误 '子查询返回的值超过1。当子查询遵循=,!=,&lt;,&lt; =,&gt;,&gt; =或子查询用作表达式时,不允许这样做。
UPDATE Table1
SET Value =
(SELECT CASE WHEN [Sub category] IS NULL THEN
CASE [Main Category] WHEN '1:Blood Pressure' THEN '1 BP'
WHEN '2:CardioVasular Disease' THEN '2 CVD'
WHEN '3:Lung Disease' THEN '3 LD'
END
ELSE CASE [Sub category]
WHEN '1.1 Blood Pressure Subcat' THEN '1.1 BP'
WHEN '2.3 CardioVasular Disease Subcat' THEN '2.3 CVD'
WHEN '3.2 Lung Diasease Subcat' THEN '3.2 LD'
END
END
FROM Table2 D
WHERE Table1.nhsnumber = D.nhsnumber )
此外,如何修改此脚本以从Table2获取最新的“注册日期”日期(最大值)。
非常感谢任何帮助。