Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 Transact-SQL (2000)
 SELECT DISTINCT with ORDER BY

Author  Topic 

adoner
Starting Member

1 Post

Posted - 2005-06-09 : 13:39:32
Does anyone know of a workaround for ordering a row by a field that is not returned in the select list? I get the error message:

SELECT DISTINCT column1, column2 FROM table1 ORDER BY column3 is what I need to do. Thanks in advance.

jsmith8858
Dr. Cross Join

7423 Posts

Posted - 2005-06-09 : 13:44:48
There is a reason why you can't do it ... consider:

Col1 Col2 Col3
---- ---- ----
Boston MA 1
Boston MA 4
Brookline MA 2
New York NY 3


How should this list be ordered if it was legal to say:

select distinct Col1, Col2 from Tbl order by Col3

?? What results do you think it should return? Should Boston be in the beginning (col3 = 1) or at the end (col3 = 4) ? It logicaly makes no sense what you are trying to do w/o altering the SELECT statement to make it very clear, most likely using GROUP BY instead of DISTINCT.

Advice -- stay away from DISTINCT in all but the rarest cases. Stick with GROUP BY. If you are not sure how GROUP BY works, it's a great time to look it up and experiment and get the hang of it.

- Jeff
Go to Top of Page
   

- Advertisement -