How to use Subquery with LIMIT and ORDER BY In SQL
Here we will add a subquery that will look for the last record match in Table B for every record in Table A with ORDER BY Descending and LIMIT options
SELECT *
FROM [Table A] A
JOIN [Table B] B ON A.PrimaryKey = B.ForeignKey
WHERE B.PrimaryKey = (
SELECT PrimaryKey
FROM [Table B]
WHERE ForeignKey = A.PrimaryKey
ORDER BY PrimaryKey DESC
OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY
);
Output:
How to Select the Last Records in a One to Many Relationship using SQL Server
In database management, one-to-many relationships are common, where a record in one table can correspond to multiple records in another table. When dealing with such relationships, it’s often necessary to select the last records from the “many” side for each record on the “one” side.
In this article, we’ll explore how to achieve this using different approaches and their examples too.