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.
where
for aggregates. E.g.(SELECT MAX(STime) FROM dbo.tb2 HAVING STime > 0)
. Or maybe rethink the code to avoid the subquery. – RLF May 28 '15 at 17:29