如何列出具有相同姓氏的所有乐队成员的姓名?
该列的值如下
band_NAME
-------------------
Carla Thomas
Stephen E. Rice
Cynthia P. Tree
Richard Anthony Paul
Ann Frances Smith
Lorace Black
Timothy Adam Paul
我知道我们必须使用instr
和substr
。我只是不知道如何确定这个位置。
我知道基本格式会像
SELECT band_NAME
FROM TABLE
where substr(band_name, ?, instr( ) IN
(select substr(band_name, ?, instr( )-1)
from table
group by SUBSTR(band_NAME , ?, INSTR( )-1 )
HAVING COUNT(* ) > 1 );
但是instr
中的问号和内部是什么?
非常感谢您的帮助!
答案 0 :(得分:0)
我假设您的名字和名字之间的分隔符是单个空格。字符串中的更多空格是姓氏的一部分。因此,您可能希望搜索第一个空格字符。
使用instr(str, substr)
返回第一次出现的子串的位置。
然后,使用substring(str, pos)
返回从给定位置开始的子字符串(由instr函数提供)。
SELECT substring(band_name, instr(band_name, ' '))
FROM yourtable
答案 1 :(得分:0)
试试这个:
SELECT t1.band_NAME
FROM TABLE t1 LEFT JOIN TABLE t2
ON SUBSTRING_INDEX(t1.band_name, ' ', - 1) = SUBSTRING_INDEX(t2.band_name, ' ', - 1)
WHERE t1.band_name <> t2.band_name
这就像你的伪代码 MySQL :
SELECT band_NAME FROM TABLE
Where FIND_IN_SET (SUBSTRING_INDEX(band_name, ' ', -1),
(Select SUBSTRING_INDEX(band_name, ' ', -1) bn
From TABLE Group by bn
having Count(bn) > 1
)
)
SQL Server
SELECT band_NAME FROM TABLE
Where
SUBSTRING(band_NAME, CHARINDEX(' ', band_NAME) + 1, LEN(band_NAME)) AS [Last Name]
IN
(Select SUBSTRING(band_NAME, CHARINDEX(' ', band_NAME) + 1, LEN(band_NAME)) AS [Last Name]
From TABLE Group by [Last Name] -- or SUBSTRING(band_NAME, CHARINDEX(' ', band_NAME) + 1, LEN(band_NAME)) AS [Last Name]
having Count(*) > 1
)
)
此外,我认为您可以通过某种方式受益于STRING_SPLIT
答案 2 :(得分:0)
试试这个
with cte as
(
select band_name, ROW_NUMBER() over(partition by SUBSTRING(band_name,CHARINDEX(' ',band_name),LEN(band_name)) order by band_name) as cnt,
SUBSTRING(band_name,CHARINDEX(' ',band_name),LEN(band_name)) as lastname
from your_table
)
select band_name
from cte
where lastname in (select lastname from cte where cnt > 1)