SQL Server – Insert When Not in Table and When Max Timestamp

sql-server-2012t-sql

I am trying to insert rows from one table to another that are not in the one I am moving them to. I also want to only move the ones that have the highest datestamp. (I want to only insert rows that are not in tb1 and have the max timestamp)

This is what I have so far:

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]));

I get this error when I execute:

Msg 147, Level 15, State 1
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.

Best Answer

I used a CTE with just one column that is the maxtime from tb2. Then join on the CTE and reference it when checking for if its the max or not.

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);