I have the following query on a populated Table variable that is supposed to return rows or each with the most recent date:
SELECT t.ID
,t.Column_2
,t.MaxDate AS [End Date Time]
,t.Column_3
,t.Column_4
,t.Column_5
FROM (
SELECT ID
,Column_2
,MAX(EndDateTime) AS MaxDate
,Column_3
,Column_4
,Column_5
FROM @MyTable
GROUP BY Column_2
) t
INNER JOIN @MyTable o ON t.ID = o.ID
AND t.MaxDate = o.EndDateTime
I keep getting the error: Column '@MyTable.ID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. Not sure what the problem is as I’m including a GROUP BY clause in the inner select statement, do I need one outter select query as well? Also, how can a modify this to ORDER BY EndDateTime DESC in the final return result?? Thank you in advance.
UPDATE:
Thank you all for your feedback, I corrected the error and learned something new. THanks.
You need to include all the columns that you are not aggregating. I think you should do the following: