Solved

SQL Server: Can i use the distinct keyword on a portion of a column?

Posted on 2010-08-16
4
221 Views
Last Modified: 2012-05-10
I have a column in a table with data such as:

001/01
001/02
002/01
002/02

I'd like to return distinct values that occur in the table on the left hand side of the "/" for slash. So the query should return the values:

001
002

I appreciate it would suggest having seperated it in 2 columns but please presume that that is not possible at this moment. The application code could do this but wanted to know if SQL could query this information.

Many thanks =)
0
Comment
Question by:paddycobbett
  • 2
4 Comments
 
LVL 16

Expert Comment

by:vdr1620
ID: 33449746
Try the below SQL

SELECT Distinct SUBSTRING('001/01',1,PATINDEX('%/%','001/01')-1)
0
 
LVL 16

Accepted Solution

by:
vdr1620 earned 300 total points
ID: 33449754
you can change it accordingly to

SELECT Distinct SUBSTRING(COLUMNNAME,1,PATINDEX('%/%',COLUMNNAME)-1)
0
 
LVL 58

Assisted Solution

by:cyberkiwi
cyberkiwi earned 200 total points
ID: 33449815
The above may give you errors if no / exist in the string.

SELECT Distinct left(col1, charindex('/',col1+'/')-1)
from tbl
0
 
LVL 1

Author Closing Comment

by:paddycobbett
ID: 33461612
Thanks guys =)
0

Featured Post

Ransomware: The New Cyber Threat & How to Stop It

This infographic explains ransomware, type of malware that blocks access to your files or your systems and holds them hostage until a ransom is paid. It also examines the different types of ransomware and explains what you can do to thwart this sinister online threat.  

Question has a verified solution.

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

Suggested Solutions

Introduction SQL Server Integration Services can read XML files, that’s known by every BI developer.  (If you didn’t, don’t worry, I’m aiming this article at newcomers as well.) But how far can you go?  When does the XML Source component become …
Slowly Changing Dimension Transformation component in data task flow is very useful for us to manage and control how data changes in SSIS.
Viewers will learn how the fundamental information of how to create a table.
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.

828 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