I'm working on northwind database.
I have to select the newest and the oldest order/orders (could be multiple with same date).
Is it possible without using subqueries and top 1, only by joining tables?
I'm working on northwind database.
I have to select the newest and the oldest order/orders (could be multiple with same date).
Is it possible without using subqueries and top 1, only by joining tables?
On
Yes you can use TOP 1 but add WITH TIES keyword.
Per MS documentation
WITH TIES Returns two or more rows that tie for last place in the limited results set. You must use this argument with the ORDER BY clause. WITH TIES might cause more rows to be returned than the value specified in expression. For example, if expression is set to 5 but two additional rows match the values of the ORDER BY columns in row 5, the result set will contain seven rows.
Exmaple
SELECT TOP 1 WITH TIES
FROM tableA A JOIN TableB
ON A.ID=B.ID
ORDER BY A.column1
Using a CTE:
Using a JOIN: