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