3

我希望有人可以在这里帮助我的语法。我有两张桌子ansicache..encountersansicache..x_refclaim_Table

encounters表有一encounterpatacctnumberx_refclaim_table.

但是,有时可能会在不同的服务日期(列)patacctnumber中出现两次。x_refclaim_tableiar_servicedate

我正在尝试将encounters表、列更新为in table = in tableadmitted的最大值iar_servicedateencounterencounterspatacctnumberx_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
      )

但它一直失败:

消息 157,级别 15,状态 1,第 1 行聚合可能不会出现在 UPDATE 语句的集合列表中。

我尝试做一些其他的事情,比如声明一个 ID,但无法让它工作。

4

2 回答 2

7

使用相关子查询

UPDATE e
SET    ADMITTED = (SELECT max(IAR_ServiceDate)
                   FROM   ansicache..x_refClaim_table x
                   WHERE  e.ENCOUNTER = x.PatAcctNumber)
FROM   ansicache..ENCOUNTERS e 
于 2013-09-26T16:53:54.033 回答
4

您可以在更新之前预先聚合您的数据。

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

另一种方法是max放入apply

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
于 2013-09-26T17:03:39.040 回答