I am trying to write a SQL query that selects multiple columns from a table with the distinct operator on one column only.
The table is simple. The columns are:
I suppose the easiest and the best solution is using OUTER APPLY. You only use one field with DISTINCT but to retrieve more data about that record, you utilize OUTER APPLY.
To test the solution, execute following query which firstly creates a temp table then retrieves data:
DECLARE @tblFruit TABLE (tblFruit_ID int, tblFruit_FruitType varchar(10), tblFruit_FruitName varchar(50))
SET NOCOUNT ON
INSERT @tblFruit VALUES (1,'Citrus ','Orange')
INSERT @tblFruit VALUES (2,'Citrus','Lime')
INSERT @tblFruit VALUES (3,'Citrus','Lemon')
INSERT @tblFruit VALUES (4,'Seed','Cherry')
INSERT @tblFruit VALUES (5,'Seed','Banana')
SELECT DISTINCT (f.tblFruit_FruitType), outter_f.tblFruit_ID
FROM @tblFruit AS f
OUTER APPLY (
SELECT TOP(1) *
FROM @tblFruit AS inner_f
WHERE inner_f.tblFruit_FruitType = f.tblFruit_FruitType
) AS outter_f
The result will be:
Citrus 1
Seed 4