我有一个包含id,first_name和last_name列的表。我想获得一个行列表,其中last_name和first_name的第一个字符重复。我在摸索,感觉到那里有一个COUNT('WHERE'),但不能完全理解。
本质上,我正在寻找可能的重复项。因此,从这个子集中:
+------+-----------+-----------+-------------+------------+
| id | firstName | lastName | dateOfBirth | createdOn |
+------+-----------+-----------+-------------+------------+
| 143 | Susie | Wong | 2015-12-01 | 2016-07-11 |
| 1268 | Dale | Armstrong | 2017-01-01 | 2017-01-04 |
| 1435 | Olive | Armstrong | 1941-03-11 | 2017-03-08 |
| 2013 | Timotini | Attilio | 1932-01-01 | 2017-08-21 |
| 2014 | Olinda | Attilio | 1938-01-01 | 2017-08-21 |
| 3076 | Sue | Armstrong | 1951-06-01 | 2018-06-22 |
| 3079 | Susan | Armstrong | 1951-09-15 | 2018-06-22 |
+------+-----------+-----------+-------------+------------+
我希望查询基于查找匹配的姓氏和匹配的名字首字母而仅返回3076和3079(Sue和Susan Armstrong),例如:
+------+-----------+-----------+-------------+------------+
| id | firstName | lastName | dateOfBirth | createdOn |
+------+-----------+-----------+-------------+------------+
| 3076 | Sue | Armstrong | 1951-06-01 | 2018-06-22 |
| 3079 | Susan | Armstrong | 1951-09-15 | 2018-06-22 |
+------+-----------+-----------+-------------+------------+
答案 0 :(得分:1)
以下是使用exists
和left
的一种选择:
select *
from yourtable y
where exists (
select 1
from yourtable y2
where y.id != y2.id
and y.lastname = y2.lastname
and left(y.firstname,1) = left(y2.firstname,1)
)
答案 1 :(得分:0)
重复的last_name
SELECT id, first_name, last_name, COUNT(*) c
FROM table
GROUP BY last_name
HAVING c > 1;
要按first_name
中的第一个字符分组,请尝试使用left()函数