Bytesized
Bytesized

Reputation: 143

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

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.

-EDIT RESOLVED

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

Upvotes: 0

Views: 124

Answers (1)

Sam Abushanab
Sam Abushanab

Reputation: 493

You could use 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 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);

Working SQL Fiddle: http://sqlfiddle.com/#!6/141bf/4

Upvotes: 2

Related Questions