简体   繁体   English

从查询中获取不同的值

[英]Getting Distinct values from query

I am on sql server.我在 sql 服务器上。

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如果mytable有以下数据

在此处输入图像描述

I would want the final query output of distinct to look like this我希望最终查询 output 看起来像这样

Mike Edward迈克·爱德华

Do you want distinct ?你想要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() .注意:除非您还想捕获名称后面的尾随空格,否则您需要 go 在substring()中空格的索引前回退一个字符。

Demo on DB Fiddle : DB Fiddle 上的演示

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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