使用 Select 语句更新或插入

Update or Insert using Select statement

我正在尝试在 SQL 服务器中编写查询,该查询执行以下操作:对一个 table 执行数据聚合查询,然后将结果传递给另一个 table。

如果具有该日期的行已经存在,则更新该列,否则插入一个新行

INSERT INTO T2 (timevalue, colValue)
    SELECT 
        Time_Stamp_Hour = DATEADD(hh, DATEPART(hh, E3TimeStamp), CAST(CAST(E3TimeStamp AS date) AS datetime)),
        AvgValue = AVG(MyValue)
    FROM
        (SELECT T1.*
         FROM T1
         WHERE (Quality) >= 0) t
    GROUP BY 
       DATEADD(hh, DATEPART(hh, E3TimeStamp), CAST(CAST(E3TimeStamp AS date) AS datetime))
       ON DUPLICATE KEY UPDATE  --TimeStamp matched
            colValue = t.AvgValue

但是,我从这个查询中得到一个语法错误:

Incorrect syntax the keyword 'ON'

不知道怎么回事。有什么想法吗?

SQL 服务器不支持 upsert 语句,您可以使用 merge:

merge T2 as target
using ( 
select Time_Stamp_Hour=dateadd(hh,datepart(hh,E3TimeStamp), cast(CAST(E3TimeStamp as date) as datetime))
        , AvgValue=AVG(MyValue)
        from (select T1.*
                 from T1
                 where (Quality) >= 0)t
        group by dateadd(hh,datepart(hh,E3TimeStamp), cast(CAST(E3TimeStamp as date) as datetime))
) as source
on target.timevalue = source.Time_Stamp_Hour 
when not matched 
insert (Time_Stamp_Hour,AvgValue)
when matched 
update set target.colValue= source.AvgValue