与另一个 table 的最大值合并

Merge with Max value of another table

我有两个 table: DestinyTablaBQ: 在SourceTabla等数据中有一列PERIODO的最大值,像这样:

    PERIODO    DATE 
    202001     01/01/2020
    202002     01/01/2020
    202003     01/01/2020
    202004     01/01/2020

还有一个来源 table,它有几百万条这样的记录:

    ANOMES
    202001
    202001
    202001
    202002
    ...
    202005    --> Missed in the DestinyTablaBQ table, Needs to be inserted or updated`

我需要创建一个 SQL 以使用源中的最大 ANOMES 值插入或更新到 DestinyTableBQ。

我使用合并创建了以下 SQL:

    MERGE [dbo].[DestinyTableBQ] BQ USING SourceTable T
    ON 
    BQ.PERIODO=MAX(T.ANOMES)
    WHEN NOT MATCHED
        THEN 
        INSERT (PERIODO,Date) 
        VALUES(MAX(T.ANOMES),'');`

但我收到以下错误:

"An aggregate cannot appear in an ON clause unless it is in a subquery contained in a HAVING clause or select list, and the column being aggregated is an outer reference."

知道如何使用合并来执行此操作吗?或者我应该如何在不合并的情况下执行此操作?

谢谢!!

你并不真的需要 merge 语法,因为你想要做的就是插入一个值,如果它不存在的话。我认为用 insert ... select ... where not exists:

表达会更简单
insert into DestinyTablaBQ (periodo)
select s.max_anomes
from (select max(anomes) max_anomes from sourceTable) s
where not exists (
    select 1 from DestinyTablaBQ bq where bq.periodo = s.max_anomes
)

如果您想使用 merge 查询,您需要先在子查询中聚合:

merge DestinyTableBQ bq
using (select max(anomes) max_anomes from sourceTable) s
on (bq.periodo = s.max_anomes)
when not matched then insert (periodo) values(s.max_anomes)