首页 > 解决方案 > SQL拆分字符串?

问题描述

我在这里阅读了很多关于拆分字符串的示例,但是没有一个真正帮助我。

我的 SQL '技能' 非常基本,但我有这个:

SELECT [ID]
,[Text]
,[Date]
FROM [dbo].[notes]
Where [Text] like '%@%'

这将返回如下数据:

| ID | Text                                      | Date                    |
|----|-------------------------------------------|-------------------------|
| 1  | the email address is someone@here.com     | 2016-05-05 00:00:00.000 |
| 2  | reach me on anotheraddress@this.com ok?   | 2020-12-20 00:00:00.000 |
| 2  | new email thisone@here.com                | 2020-12-21 00:00:00.000 |
| 3  | oneeamil@here.com anotheremail@there.com  | 2021-01-20 00:00:00.000 |

我希望按日期过滤/分组以获取最新条目并将重复项拆分到列表中,例如

| ID | Email                  |
|----|------------------------|
| 1  | someone@here.com       |
| 2  | thisone@here.com       |
| 3  | oneeamil@here.com      |
| 3  | anotheremail@there.com |

我很感激任何帮助

谢谢 :)

标签: sqlsplit

解决方案


如果您使用的是 SQL Server 2016 或更高版本,并且只想要看起来像电子邮件的空格分隔字符串,那么您可以使用string_split()

select n.*, s.value
from dbo.notes n cross apply
     string_split(n.text, ' ') s
where s.value like '%@%';

如果您希望这仅限于每个 id 的最新行:

select n.*, s.value
from (select n.*,
             row_number() over (partition by id order by date desc) as seqnum
      from dbo.notes n
     ) n cross apply
     string_split(n.text, ' ') s
where n.seqnum = 1 and s.value like '%@%';

是一个 db<>fiddle。


推荐阅读