2013-09-26 57 views
2

我希望有人可以在這裏幫助我的語法。 我有兩個表ansicache..encountersansicache..x_refclaim_Table更新聲明包含聚合在SQL服務器中不起作用

encounters表有在x_refclaim_tablepatacctnumber列相匹配的encounter列。

但是,有時patacctnumber可能會在x_refclaim_table中顯示兩次,並顯示不同的服務日期(第iar_servicedate列)。

我想給encounters表,admitted列更新爲iar_servicedate的最高值,其中在encountersencounter = patacctnumberx_refclaim

update ansicache..ENCOUNTERS 
     set ADMITTED=max(IAR_ServiceDate) 
from 
    (
     ansicache..ENCOUNTERS e (nolock) 
      join 
     ansicache..x_refClaim_table x (nolock) 
      on e.ENCOUNTER=x.PatAcctNumber 
    ) 

它保持雖未能:

Msg 157,Level 15,State 1,Line 1 集合可能不會出現在UPDATE語句的集合列表中。

我試着做一些其他的東西,如聲明一個ID,但無法讓它工作。

回答

5

使用相關子查詢

UPDATE e 
SET ADMITTED = (SELECT max(IAR_ServiceDate) 
        FROM ansicache..x_refClaim_table x 
        WHERE e.ENCOUNTER = x.PatAcctNumber) 
FROM ansicache..ENCOUNTERS e 
3

可以更新之前preaggreagate您的數據。

update ansicache..ENCOUNTERS set 
    ADMITTED = x.IAR_ServiceDate 
from ansicache..ENCOUNTERS as e 
    inner join (
     select 
      x.PatAcctNumber, max(x.IAR_ServiceDate) as IAR_ServiceDate 
     from ansicache..x_refClaim_table as x 
     group by x.PatAcctNumber 
    ) as x on x.PatAcctNumber = e.ENCOUNTER 

它通常是更優選的方法對我來說不是子查詢,因爲你可以使用max(...)幾次,如果你需要它,或者,你還可以使用其他的集合體,所以它更容易在將來維護這個查詢:

update ansicache..ENCOUNTERS set 
    ADMITTED = x.IAR_ServiceDate, 
    ADMITTED2 = dateadd(dd, 5, x.IAR_ServiceDate2) 
from ansicache..ENCOUNTERS as e 
    inner join (
     select 
      x.PatAcctNumber, 
      max(x.IAR_ServiceDate) as IAR_ServiceDate, 
      min(x.IAR_ServiceDate) as IAR_ServiceDate2 
     from ansicache..x_refClaim_table as x 
     group by x.PatAcctNumber 
    ) as x on x.PatAcctNumber = e.ENCOUNTER 

另一種方式做,這是把maxapply

update ansicache..ENCOUNTERS set 
    ADMITTED = x.IAR_ServiceDate, 
    ADMITTED2 = dateadd(dd, 5, x.IAR_ServiceDate2) 
from ansicache..ENCOUNTERS as e 
    cross apply (
     select 
      max(x.IAR_ServiceDate) as IAR_ServiceDate, 
      min(x.IAR_ServiceDate) as IAR_ServiceDate2 
     from ansicache..x_refClaim_table as x 
     where x.PatAcctNumber = e.ENCOUNTER 
    ) as x