简体   繁体   中英

Getting Distinct values from query

I am on sql server.

My goal is to parse the name field based on the first space in the name field then get a distinct list of names

I have the parsed the name out with the below code

SELECT substring(name, 1, CHARINDEX(' ' , name))
From mytable

I am having trouble getting the distinct list of names from the above query result. Would someone tell me what correct syntax is to do this?

As example

If mytable has the following data

在此处输入图像描述

I would want the final query output of distinct to look like this

Mike Edward

Do you want distinct ?

select distinct substring(name, 1, charindex(' ' , name) - 1) name from mytable

Note: unless you want to capture also the trailing space after the name, you need to go back one character before the index of the space in substring() .

Demo on DB Fiddle :

| name   |
| :----- |
| Edward |
| Mike   |

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM