Link to home
Start Free TrialLog in
Avatar of Murray Brown
Murray BrownFlag for United Kingdom of Great Britain and Northern Ireland

asked on

SQL Get distinct list from any query

Hi

I want to get a distinct list from any query such as the one below

Select * From Customers Where [Company] >= 'Company A' And [Company] <= 'Company G'

I tried the following but get the error Incorrect syntax near ')'.

Select Distinct Company From (Select * From Customers Where [Company] >= 'Company A' And [Company] <= 'Company G')
Avatar of FarWest
FarWest

Select distinct works on result set row level so it will get only one row of any repeated row
Specifying column name only works whith aggregation function like Count
Avatar of Nakul Vachhrajani
Try this:

Select Distinct t.Company From (Select * From Customers Where [Company] >= 'Company A' And [Company] <= 'Company G') AS t

(I don't have a SQL Server instance readily accessible - I'll share a working example as soon as I have one).

Bascially, SQL Server is looking for a table alias that is can use for the outer query.
SOLUTION
Avatar of Nakul Vachhrajani
Nakul Vachhrajani
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>>"I want to get a distinct list from any query ..."

Please be careful with the notion that any query is suited to use of "SELECT DISTINCT"
"SELECT DISTINCT" is the enemy of performance, it should be used sparingly.
IF used, do it with as few columns as possible.

see "Select Distinct is returning duplicates" in particular the “Hail Mary Distinct”
There are 2 references at the end of that article I recommend too.
Avatar of Murray Brown

ASKER

Thanks very much