Search code examples
t-sql

DISTINCT select statement but return rows in original sort order?


I have a list of Attributes of which there are duplicates. I need to return a distinct list of the attributes but preserving the original sort order. So in y example below I need to return...

Zebra Apple Ball

Any help would be appreciated.

DECLARE @Attributes TABLE (ID INT, Attribute VARCHAR(50))
INSERT INTO @Attributes (ID, Attribute) VALUES (1, 'Zebra'),(2, 'Apple'),(3, 'Ball'),(4, 'Zebra'),(5, 'Ball')
SELECT DISTINCT Attribute FROM @Attributes

Solution

  • I'm not sure why I did not consider grouping to resolve this! Thanks to @allmhuran who made a suggestion that works perfectly.

    select Attribute from @Attributes group by Attribute order by min(ID);