Solved

SQL Get distinct list from any query

Posted on 2015-02-22
6
75 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:Murray Brown
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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 14

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 14

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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 49

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 49

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:Murray Brown
ID: 40653241
Thanks very much
0

Featured Post

PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

Question has a verified solution.

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

In this article we will learn how to fix  “Cannot install SQL Server 2014 Service Pack 2: Unable to install windows installer msi file” error ?
In part one, we reviewed the prerequisites required for installing SQL Server vNext. In this part we will explore how to install Microsoft's SQL Server on Ubuntu 16.04.
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
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.

623 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