Solved

SQL Get distinct list from any query

Posted on 2015-02-22
6
69 Views
Last Modified: 2015-03-08
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')
0
Comment
Question by:murbro
6 Comments
 
LVL 12

Expert Comment

by:FarWest
ID: 40623992
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
0
 
LVL 13

Expert Comment

by:Nakul Vachhrajani
ID: 40624041
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.
0
 
LVL 13

Assisted Solution

by:Nakul Vachhrajani
Nakul Vachhrajani earned 250 total points
ID: 40624057
Here's an example:
USE tempdb;
GO
DECLARE @Customers TABLE (CustomerId INT IDENTITY(1,1) NOT NULL,
                          CustomerName NVARCHAR(50) NOT NULL,
                          Company NVARCHAR(50) NOT NULL
                        );

INSERT INTO @Customers (CustomerName, Company)
VALUES ('Customer1',1),
       ('Customer2',1),
       ('Customer3',1),
       ('Customer4',2),
       ('Customer5',3),
       ('Customer6',4),
       ('Customer7',3)

Select DISTINCT t.Company 
FROM (SELECT * 
      FROM @Customers 
      WHERE [Company] >= 1 
        AND [Company] <= 3
     ) AS t;
GO

Open in new window


NOTE:
Company Names are alphanumeric. So, the greater than/less than operators will not work if you only want companies whose names are Company A, B, C, D, E, F and G. To do this, you will have to either use an IN clause or use Id values (like what I have done in my quick example)
Also, you don't really need a sub-query. With the same example code as above, the following query will also return the same results

SELECT DISTINCT c.Company
FROM @Customers AS c
WHERE c.Company BETWEEN 1 AND 3;
GO

Open in new window

0
Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

 
LVL 48

Accepted Solution

by:
PortletPaul earned 250 total points
ID: 40624945
You can use >= or <= with strings (or between can be used, it is the same). The following are functionally the same:

SELECT DISTINCT
       Company 
FROM Customers
WHERE [Company] >= 'Company A' And [Company] <= 'Company G'
;

SELECT DISTINCT
       Company 
FROM Customers
WHERE [Company] BETWEEN 'Company A' AND 'Company G'
;

Open in new window


for some sample data:
CREATE TABLE Customers
	([Company] varchar(60))
;
	
INSERT INTO Customers
	([Company])
VALUES
	('Company A'),	('Company B'),	('Company C'),
	('Company D'),	('Company E'),	('Company F'),	('Company G'),

	('Company H'),	('Company I'),	('Company Z')
;

Open in new window


The results of both queries are:
|   COMPANY |
|-----------|
| Company A |
| Company B |
| Company C |
| Company D |
| Company E |
| Company F |
| Company G |

Open in new window


But note that a [Company] of 'Aardvark Inc' is not be BETWEEN 'Company A' AND 'Company G'
(i.e. the use of >= and <= on strings may not meet your expectations)
0
 
LVL 48

Expert Comment

by:PortletPaul
ID: 40624995
>>"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.
0
 

Author Closing Comment

by:murbro
ID: 40653241
Thanks very much
0

Featured Post

Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Slowly Changing Dimension Transformation component in data task flow is very useful for us to manage and control how data changes in SSIS.
The Delta outage: 650 cancelled flights, more than 1200 delayed flights, thousands of frustrated customers, tens of millions of dollars in damages – plus untold reputational damage to one of the world’s most trusted airlines. All due to a catastroph…
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question