Solved

SQL Get distinct list from any query

Posted on 2015-02-22
6
61 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 11

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 11

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
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
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

Free Gift Card with Acronis Backup Purchase!

Backup any data in any location: local and remote systems, physical and virtual servers, private and public clouds, Macs and PCs, tablets and mobile devices, & more! For limited time only, buy any Acronis backup products and get a FREE Amazon/Best Buy gift card worth up to $200!

Join & Write a Comment

In this article—a derivative of my DaytaBase.org blog post (http://daytabase.org/2011/06/18/what-week-is-it/)—I will explore a few different perspectives on which week today's date falls within using Microsoft SQL Server. First, to frame this stu…
I wrote this interesting script that really help me find jobs or procedures when working in a huge environment. I could I have written it as a Procedure but then I would have to have it on each machine or have a link to a server-related search that …
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.
Via a live example, show how to setup several different housekeeping processes for a SQL Server.

759 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

18 Experts available now in Live!

Get 1:1 Help Now