Solved

SQL Get distinct list from any query

Posted on 2015-02-22
6
63 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 12

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 12

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
VMware Disaster Recovery and Data Protection

In this expert guide, you’ll learn about the components of a Modern Data Center. You will use cases for the value-added capabilities of Veeam®, including combining backup and replication for VMware disaster recovery and using replication for data center migration.

 
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

Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Converting Teradata SQL to Oracle SQL (exadata) 3 28
SQL Login 17 37
T-SQL:  Negative Numbering in CTE Is Not Working 2 27
ms sql last 8 weeks as columns 5 7
Why is this different from all of the other step by step guides?  Because I make a living as a DBA and not as a writer and I lived through this experience. Defining the name: When I talk to people they say different names on this subject stuff l…
JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
Familiarize people with the process of utilizing SQL Server functions from within Microsoft Access. Microsoft Access is a very powerful client/server development tool. One of the SQL Server objects that you can interact with from within Microsoft Ac…
Via a live example, show how to setup several different housekeeping processes for a SQL Server.

932 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

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now