帮我正确地执行此SQL更新查询

时间:2010-07-02 18:28:53

标签: sql-server optimization

我有3个值需要从一个表复制到另一个表。这是我的业余尝试,我知道这是非常不公平的,这种查询的正确方法是什么?

  update [IDAT_PATIENTS] 
  set TargetRabiesSerial = 
    (select top 1 SERIAL_NUMBER 
     from [IDAT_RABIESHISTORY] as rab 
     where TargetPetAccountNum = rab.PATIENT_ACCOUNT_ID 
        and TargetClientAccountNum = rab.CLIENT_ACCOUNT_ID 
     order by rab.DATE_TIME_PERFORMED desc)
  , TargetRabiesBrandName = 
    (select top 1 BRAND_NAME 
     from [IDAT_RABIESHISTORY] as rab 
     where TargetPetAccountNum = rab.PATIENT_ACCOUNT_ID 
        and TargetClientAccountNum = rab.CLIENT_ACCOUNT_ID 
     order by rab.DATE_TIME_PERFORMED desc)
  , TargetRabiesTag = 
    (select top 1 TAG_NUMBER 
     from [IDAT_RABIESHISTORY] as rab 
     where TargetPetAccountNum = rab.PATIENT_ACCOUNT_ID 
        and TargetClientAccountNum = rab.CLIENT_ACCOUNT_ID 
     order by rab.DATE_TIME_PERFORMED desc)
  where TargetClientAccountNum in 
    (select CLIENT_ACCOUNT_ID 
     from [IDAT_RABIESHISTORY] 
     where TargetPetAccountNum = PATIENT_ACCOUNT_ID)

2 个答案:

答案 0 :(得分:3)

试试这个:

  Update p Set
     TargetRabiesSerial = h.SERIAL_NUMBER,
     TargetRabiesBrandName =  h.BRAND_NAME,  
     TargetRabiesTag = h.TAG_NUMBER   
  From IDAT_PATIENTS p
      Join IDAT_RABIESHISTORY h
          On h.PATIENT_ACCOUNT_ID = p.TargetPetAccountNum
             And h.CLIENT_ACCOUNT_ID = p.TargetClientAccountNum 
             And h.DATE_TIME_PERFORMED = 
                    (Select Max(DATE_TIME_PERFORMED)
                     From IDAT_RABIESHISTORY 
                     Where h.CLIENT_ACCOUNT_ID = p.TargetClientAccountNum 
                         And h.CLIENT_ACCOUNT_ID = p.TargetClientAccountNum)
  Where TargetClientAccountNum In  
    (Select CLIENT_ACCOUNT_ID  
     From IDAT_RABIESHISTORY  
     Where TargetPetAccountNum = PATIENT_ACCOUNT_ID) 

答案 1 :(得分:0)

或多或少像这样的东西,没有要验证的模式,所以请仔细检查语法:)

update [IDAT_PATIENTS] 
    set TargetRabiesSerial = tblLatestHistory.SERIAL_NUMBER,
    TargetRabiesBrandName = IDAT_RABIESHISTORY,
    TargetRabiesTag = IDAT_RABIESHISTORY
from [IDAT_PATIENTS]
inner join (
    select PATIENT_ACCOUNT_ID, CLIENT_ACCOUNT_ID, SERIAL_NUMBER, BRAND_NAME, TAG_NUMBER, max(DATE_TIME_PERFORMED) 
    from IDAT_RABIESHISTORY
    group by  PATIENT_ACCOUNT_ID, CLIENT_ACCOUNT_ID, SERIAL_NUMBER, BRAND_NAME, TAG_NUMBER
) tblLatestHistory
on TargetPetAccountNum = tblLatestHistory.PATIENT_ACCOUNT_ID 
and TargetClientAccountNum = tblLatestHistory.CLIENT_ACCOUNT_ID