如何根据案例条件更新表

时间:2014-07-29 19:33:29

标签: sql sql-server join sql-update case

我有4张桌子。

  • PRIMARYCASE_ID, ADDRESS, COUNTRY
  • SECONDARYCASE_ID, ADDRESS, COUNTRY
  • DESTCASE_ID, PRIMARY_ADDRESS, SECONDARY_ADDRESS, PRIMARY_COUNTRY, SECONDARY_COUNTRY
  • COUNTRIESCOUNTRY, RISK_SCORE

更新查询:

update d
set d.PRIMARY_ADDRESS= ...?
    ,d.PRIMARY_COUNTRY= ...?
    ,d.SECONDARY_ADDRESS= ...?
    ,d.SECONDARY_COUNTRY= ...?
from DEST d
join PRIMARY p
on p.CASE_ID=d.CASE_ID
join SECONDARY s
on s.CASE_ID=d.CASE_ID
join COUNTRIES c
... ??? 

我必须根据{DESTPRIMARY的最高地址,更新SECONDARY表的地址和国家/地区列以及risk_scoreCOUNTRIES表的相应列1}}表。 Risk_Score的值介于0到100之间。

CASE_IDCOUNTRY列可用作连接列。请帮忙。

1 个答案:

答案 0 :(得分:0)

这是获取数据的基本选择语句。您可以将其用作内部查询并加入目标表并执行更新 -

SELECT * 
FROM 
(SELECT 
  P.CASE_ID, P.ADDRESS PRIM_ADDRESS, P.COUNTRY PRIM_COUNTRY, 
  ROW_NUMBER() OVER (PARTITION BY CASE_ID ORDER BY RISK_SCORE DESC) AS RN_PRIMARY
  FROM [PRIMARY] P JOIN COUNTRIES C
  ON P.COUNTRY = C.COUNTRY)PRIMARYVALUES
JOIN 
(SELECT P.CASE_ID, P.ADDRESS SEC_ADDRESS, P.COUNTRY SEC_COUNTRY, 
  ROW_NUMBER()    OVER (PARTITION BY CASE_ID ORDER BY RISK_SCORE DESC) AS RN_SECONDARY
  FROM [SECONDARY] P JOIN COUNTRIES C
  ON P.COUNTRY = C.COUNTRY)SECONDARYVALUES 
 ON PRIMARYVALUES.CASE_ID = SECONDARYVALUES.CASE_ID
WHERE RN_PRIMARY = 1 AND RN_SECONDARY = 1

这是SQLFiddle - http://sqlfiddle.com/#!3/49642b/2