0
votes

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

1
what are you trying to do here? Why would you have Max(dob) in the datediff? - S3S
What part of that error message is not clear? You can't have an aggregate in the where clause. hint...MAX. - Sean Lange
update your question add a proper data sample and the expected result - ScaisEdge
edited. please find. - sandy
Sorry, your question doesn't make any sense. I think you will need to post sample data and desired results to possibly make it clear. - Tab Alleman

1 Answers

1
votes

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.