sandy
sandy

Reputation: 1

subquery aggregation issue

having issues for below query:

SELECT * 
FROM   [projectuser].[dbo].[newdataset] 
WHERE  ( Datediff(s, '1970-01-01 00:00:00', Max(dob)) ) 
       >= 
       (SELECT Datediff(s, '1970-01-01 00:00:00', Max(dob)) - 3600 
        FROM [projectuser].[dbo].[sqlquries7]) 
ORDER  BY dob 

Error message:

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.

based on Change data capture, trying to select 1 hour records(source) from current max date(target) that is in epoch date time (converting datetime to epoch). outer query would be source and inner query is target Please help me. Thank you

Upvotes: 0

Views: 49

Answers (1)

Laughing Vergil
Laughing Vergil

Reputation: 3766

Rethink your query. You have one calculated value from an external source, and one calculated value from an internal source. You are using MAX with no GROUP BY, indicating a single value from each table is to be compared. If the value Datediff(s, '1970-01-01 00:00:00', Max(dob)) that is greater than the value returned by (SELECT Datediff(s, '1970-01-01 00:00:00', Max(dob)) - 3600 FROM [projectuser].[dbo].[sqlquries7]), then all rows from [projectuser].[dbo].[newdataset] will be returned.

That is, if your existing logic worked.

So a definition of what you are actually looking for is the first thing you need to do. This should include what rows you are looking for (i.e. all rows in newDataSet where the dob is after the value calculated from the sqlqueries table.

Note that the way to use the single value from the sqlqueries table is to either (1) place the result in a variable, e.g.:

DECLARE @mdob datetime
SELECT @mdob = Datediff(s, '1970-01-01 00:00:00', Max(dob)) - 3600 
        FROM [projectuser].[dbo].[sqlquries7]

Or to create a derived table with the single value, and CROSS JOIN it to the other recordset, e.g.:

SELECT * 
FROM   [projectuser].[dbo].[newdataset] nds
CROSS JOIN (
    SELECT Datediff(s, '1970-01-01 00:00:00', Max(dob)) - 3600 AS Cutoff
    FROM [projectuser].[dbo].[sqlquries7]) as Tbl
WHERE  ( Datediff(s, '1970-01-01 00:00:00', dob) ) >= Cutoff

But remember - MAX in a WHERE clause (or MIN, SUM, etc) is not allowed except in specific, narrowly defined cases. If you need a MAX() value in your WHERE clause, it must be calculated somewhere else.

Upvotes: 1

Related Questions