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] 
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.

  • MAX(STime) is an aggregate. The message said you need a HAVING clause, which is a 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

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
FROM tb2 
INNER JOIN aggregateTime ON 1=1
WHERE tb2.STime = aggregateTime.maxTime AND EMPNO NOT IN (SELECT EMPNO FROM tb1);

I think this does what you need but you may want to replace the NOT EXISTS by making the statement into a MERGE statement.

         ,MAX(STime) OVER() AS MAX_STime

  FROM   [db].[dbo].tb2
INSERT INTO [db].[dbo].[tb1] 
FROM   CTE_Tb2 t2
WHERE  STime = MAX_STime
                        SELECT 1 
                        FROM   [db].[dbo].[tb1] t1
                        WHERE  t1.EMPNO = t2.EMPNO
  • It gives me this error: Msg 213, Level 16, State 1, Line 1 Column name or number of supplied values does not match table definition. – Bytesized May 28 '15 at 17:50
  • Yes I can't see which columns are in your tables so add them to the CTE and replace t2.* with your column names. Or post the schema and I will update the code – James Anderson May 28 '15 at 18:18
  • I figured it out. – Bytesized May 28 '15 at 18:19
  • If you figured it out you can post an answer to your own question and accept it – Tom V May 28 '15 at 18:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.