sql-server - 如何从 SQL 中的字符串中删除一组单词?
问题描述
我的表中有一个列,如下所示:
Column 1
-------------------------
Space Planning April 2019
Space Décor Planning May 2020
Hidden September 2018
如何查询以从列中删除月份和年份单词以显示类似的结果
Column 1
------------------------
Space Planning
Space Décor Planning
Hidden
一般来说,如何使用 SQL 从列中的字符串中动态过滤掉单词。
解决方案
“一般”的方法是首先确定一些可识别的模式,该模式适用于您的特定案例中的所有数据。然后你编写利用该模式的代码。是的,我知道这听起来很奇怪。让我解释。
在您的情况下,您似乎有以下形式的模式:“某种数据”,然后是空格,然后是月份名称,然后是空格,然后是 4 位数年份。这种模式总是一致的吗?最后总是有一个4位数的年份吗?你能确定吗?如果是这样,那么您可以通过查找距值末尾超过 5 个字符的第一个空格的位置来删除月份名称和年份(这将是“数据”和“月份名称”之间的空格),然后删除它以及之后的所有内容。这是您如何做到这一点的示例。这不是唯一的方法,我试图写一个你能理解的算法。由内而外阅读!:
declare @somedata varchar(64) = 'Space Planning May 2019'
select left
(
@somedata,
len(@somedata) - 5 - charindex -- the length of the string excluding the data below
(
' ', -- look for the first space character
reverse -- reverse it
(
left -- get all but the last 5 characters of the value
(
@somedata,
len(@somedata) - 5
)
)
)
)
yourColumn
要为我假设为名为的表中调用的整个列获取此结果YourTable
,只需添加 from 子句并将变量替换为实际的列名:
select newColumn = left
(
yourColumn,
len(yourColumn) - 5 - charindex -- the length of the string excluding the data below
(
' ', -- look for the first space character
reverse -- reverse it
(
left -- get all but the last 5 characters of the value
(
yourColumn,
len(yourColumn) - 5
)
)
)
)
from YourTable
推荐阅读
- javascript - 在 Node.js 中将 setTimeout 与请求包一起使用
- asp.net - 在一行中设置验证码图像和文本框
- php - 通过下拉列表过滤数据库表
- php - 使用 SET 数据类型和 PDO 调用 MySql 存储过程时出现错误 'Data truncated for column ...'
- vim - 如何将 Vim 命令保存到特定缓冲区并再次使用它们
- php - 为什么 PHP setcookie 可以在 localhost 上工作,但不能在浏览器上工作?
- python-3.x - OSError:Errno 30 只读文件系统:有什么方法可以在 AWS Lambda 中创建 CSV 并将其附加到来自 Python 的电子邮件?
- html - 在 ` 中输入文本字段
- mongodb - 获取给定用户的每个对话的未读消息计数
- go - pubsub.NewClient 卡在开发机器和 docker 中