T-SQL 当不在 table 和最大时间戳时插入 Issue

T-SQL Insert when not in table and when max timestamp Issue

我正在尝试将行从一个 table 插入到另一个不在我要将它们移动到的行中。我还想只移动具有最高日期戳的那些。 (我只想插入不在 tb1 中且具有最大时间戳的行)

这是我目前拥有的:

INSERT INTO [db].[dbo].[tb1]
SELECT *
FROM   tb2
WHERE ( dbo.tb2.STime = (SELECT Max(STime)
                         FROM   dbo.tb2) )
      AND ( EMPNO NOT IN (SELECT EMPNO
                          FROM   [db].[dbo].[tb1]) ); 

我在执行时遇到此错误:

Msg 147, Level 15, State 1, Line 43 An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.

-编辑 已解决

WITH aggregateTime (maxTime) AS (
SELECT MAX(STime) AS maxTime 
FROM tb2
)
INSERT INTO db.dbo.tb1
SELECT *
FROM tb2 
INNER JOIN aggregateTime ON 1=1
WHERE tb2.STime = aggregateTime.maxTime AND EMPNO NOT IN (SELECT EMPNO FROM tb1);

您可以使用只有一列的 CTE,即来自 tb2 的最大时间。然后加入 CTE 并在检查它是否为最大值时引用它。

WITH aggregateTime (maxTime) AS (
    SELECT MAX(STime) AS maxTime 
    FROM tb2
)
INSERT INTO tb1 (id, EMPNO, Street1)
SELECT id, EMPNO, Street1
FROM tb2 
INNER JOIN aggregateTime ON 1=1
WHERE tb2.STime = aggregateTime.maxTime AND EMPNO NOT IN (SELECT EMPNO FROM tb1);

工作SQLFiddle:http://sqlfiddle.com/#!6/141bf/4