Sql – How to write this SQL query

sql

I have a table that records a history of child items linked to a parent, with two columns:

  • ParentId
  • ChildId

Some example data looks like this:

ParentId — ChildId
001 — 001
001 — 001
001 — 001
001 — 002
001 — 002
001 — 002
001 — 003
001 — 003
001 — 003
001 — 003
001 — 004
001 — 004
001 — 005
001 — 005
001 — 005
001 — 005

I need to select all the rows with the highest value ChildId for a given ParentId. So in the above example, I need the query to return the following rows, given an input parameter of '@parentId = 001':

001 — 005
001 — 005
001 — 005
001 — 005

Thanks for any help!

Best Answer

This aught to do it:

SELECT * FROM MyTable
WHERE parentId = '001'
AND childId = (SELECT MAX(childId) FROM MyTable WHERE parentId = '001')