About this question
I have a simple query that I just want to return the most recent date for. I can't figure out why I can't do this:
I have a simple query that I just want to return the most recent date for. I can't figure out why I can't do this:
Log in to share your answer and help other learners.
Log in to answerBest Answer · By JanBask MS SQL Server Expert
Answered on Apr 14, 2021
It looks to me like you don't quite understand how to use GROUP BY which is why you are facing sql server max date error in your coding.
A query with GROUP BY will identify the unique sets of values for the grouped-by columns, and then will allow you to use aggregate functions on any other rows in the data set.
I'll assume that, for each part # and description, you want the date of the most recent change in cost, and what that cost was.
#latest_price_change (part_no varchar(20), part_desc varchar(250), recalc_date datetime) INSERT INTO #latest_price_change (part_no, part_desc, recalc_date) SELECT pvp.part_no, pvp.name, MAX(pc.recalc_date) FROM part_v_part as pvp JOIN part_v_part_cost as pc ON pvp.part_key = pc.part_key WHERE pvp.part_status <> 'inactive' AND pvp.part_status <> 'obsolete' AND pvp.part_source_key = '373' AND pvp.part_no = '90-0018' GROUP BY pvp.part_no, pvp.name SELECT lpc.part_no as 'Part No.', lpc.part_desc as 'Description', lpc.recalc_date as 'Previous Update', pc.cost as 'Previous Std. Cost' FROM #latest_price_change as lpc JOIN part_v_part as pvp ON lpc.part_no = pvp.part_no AND lpc.part_desc = pvp.name JOIN part_v_part_cost as pc ON pvp.part_key = pc.part_key AND lpc.recalc_date = pc.recalc_dateAfter setting up a part_v_part and a part_v_part_cost table that returned the same three lines as yours did when using your query, I just got back the last line with my query. FYI - I tested this with MS SQL Server 2012. Hope this helps.
Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.
Step-by-step SQL Server guides from industry experts
Common SQL Server interview questions, answered
Guides, tips and career advice on SQL Server from JanBask experts.
SQL Server Top 75 SSAS Interview Questions and Answers For Beginners & Experts
Prepare for your SSAS interview with our comprehensive guide featuring 75 top SQL Server Analysis Services interview questions…
SQL Server How to Become a SQL Database Administrator?
How to become a sql database administrator In 2025, discover what these professionals do, explore how much they earn and learn…
SQL Server OLAP vs OLTP: Key Differences, Architectures, Performance & Real-World Examples
Compare OLTP vs OLAP with clear definitions, architecture diagrams, real-world examples, and FAQs. Learn when to use each system…
SQL Server 70+ Most Asked SSIS Interview Questions for Freshers & Experienced
Prepare for your next SQL Server Integration Services (SSIS) interview with our top 70+ SSIS interview questions and answers.…