I need to create a query that returns only the rows which have the minimum values in a specific column.
I have this results (example):
Name | Description | Order
-----------------------------
Name1 | A | 1
Name1 | B | 2
Name1 | C | 3
Name2 | A | 1
Name2 | B | 2
Name2 | C | 3
Name | Description | Order
-----------------------------
Name1 | A | 1
Name2 | A | 1
Select Top 1 *
From table1
Where Name = 'Name1'
Order by Order
Select *
From table1
Where Name = 'Name1'
and order = (Select min(Order)
From table1
Where Name = 'Name1')
You're close on the second query if you want to use a simple subquery:
Select *
From table1 t1
WHERE [order] = (Select min([Order])
From table1
Where Name = t1.Name)
You can also use partitioning functions to find the "first" record for each group:
SELECT Name, Description, [Order] FROM
(SELECT *,
ROW_NUMBER() OVER(ORDER BY [Order] PARTITION BY Name) RowNum
FROM Table1
) A
WHERE RowNum = 1