简体   繁体   English

SQL获取不同的名字和姓氏

[英]SQL get distinct first name and last name

I have this query here select distinct id, FirstName, LastName from table 我在这里有此查询select distinct id, FirstName, LastName from table

This returns me a list of people, first some of the ids were returning duplicates, but I used distinct to fix that, but I still have an issue and that some of the people are duplicates. 这返回了我的人员列表,首先某些ID返回了重复项,但是我使用了distinct来解决此问题,但是我仍然遇到问题,有些人是重复项。

Is there also away to put a distinct on the first and last name as well as id? 还可以在名字和姓氏以及ID上加上区别吗? (Some results do not come with an id) (某些结果没有ID)

Results (without distinct id): 结果(无唯一ID):

id - 01 - firstname - james - lastname - smith
id - 01 - firstname - james - lastname - smith
id - 02 - firstname - john - lastname - hicks
id - 02 - firstname - john - lastname - hicks
id -    - firstname - tom - lastname - nicks
id -    - firstname - tom - lastname - nicks

Expecting: 期望:

id - 01 - firstname - james - lastname - smith
id - 02 - firstname - john - lastname - hicks
id -    - firstname - tom - lastname - nicks

You have duplicates because you are including id in the select : 您有重复项,因为您在select中包含了id

select distinct FirstName, LastName
from table;

If you need an id for a name, then use group by : 如果您需要名称的id ,请使用group by

select min(id) as id, FirstName, LastName
from table
group by FirstName, LastName;

EDIT: 编辑:

If you are still getting duplicates with these queries, then you have characters in the names that are throwing things off. 如果这些查询仍然存在重复项,则名称中会有字符,这些字符会使您无法正常运行。 I would start by trimming leading and trailing spaces to see if this fixes the duplicates problem: 我将从修剪前导和尾随空格开始,看看这是否可以解决重复项问题:

select min(id) as id, trim(FirstName) as FirstName, trim(LastName) as LastName
from table
group by trim(FirstName), trim(LastName);

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

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