我在这里搜索了许多问题,但我发现的所有问题的答案都是针对不同的语言,如 Javascript 等。
我在 SQL 中有一个简单的任务,我似乎找不到简单的方法来做。
我只需要计算 SQL 字符串(一个句子)中“单词”的数量。你可以看到为什么在我的例子中“words”用引号引起来。 “单词”由空格分隔。
例句:
1. I am not your father.
2. Where are your brother,sister,mother?
3. Where are your brother, sister and mother?
4. Who are you?
想要的答案:
1. 5
2. 4
3. 7
4. 3
如您所见,我需要计算不考虑符号的“单词”(我必须将它们视为单词的一部分)。所以在样本号中。 2:
(1)Where (2)are (3)your (4)brother,sister,mother? = 4
我可以通过执行这样的替换来处理多个空格:
REPLACE(string, ' ', ' ') -> 2 whitespaces to 1
REPLACE(string, ' ', ' ') -> 3 whitespaces to 1 and so on..
我可以使用什么 SQL 函数来执行此操作?我使用 SQL Server 2012,但需要一个也能在 SQL Server 2008 中运行的函数。
最佳答案
这是一种方法:
创建并填充示例表( 请 保存是您以后问题中的这一步)
DECLARE @T AS TABLE
(
id int identity(1,1),
string varchar(100)
)
INSERT INTO @T VALUES
('I am not your father.'),
('Where are your brother,sister,mother?'),
('Where are your brother, sister and mother?'),
('Who are you?')
使用 cte 将多个空格替换为单个空格(感谢 Gordon Linoff 的回答 here)
;WITH CTE AS
(
SELECT Id,
REPLACE(REPLACE(REPLACE(string, ' ', '><' -- Note that there are 2 spaces here
), '<>', ''
), '><', ' '
) as string
FROM @T
)
查询CTE-字符串长度-不带空格的字符串长度+1:
SELECT id, LEN(string) - LEN(REPLACE(string, ' ', '')) + 1 as CountWords
FROM CTE
结果:
id CountWords
1 5
2 4
3 7
4 3
关于sql-server - SQL 字符串 : Counting Words inside a String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41952250/