我在这里搜索了许多问题,但我发现所有体面的答案是不同的语言,如Javascript等。
我在SQL中有一个简单的任务,但我似乎找不到一个简单的方法来完成。我只需要计算一个SQL字符串(一个句子)中“单词”的数量。在我的示例中,您可以看到为什么“单词”用引号括起来。“单词”用白色分隔。
例句:
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中也能工作的函数。
4条答案
按热度按时间vecaoik11#
下面是一种方法:
创建并填充示例表(请保存此步骤,以备将来提问)
使用CTE将多个空格替换为单个空格(感谢Gordon Linoff的回答here)
查询CTE -字符串长度-不含空格的字符串长度+ 1:
结果:
bd1hkmkf2#
这是对@ZoharPeled答案的一个小改进,它也可以处理0长度值:
zpjtge223#
也要处理多个空间,请使用下面显示的方法
https://exploresql.com/2018/07/31/how-to-count-number-of-words-in-a-sentence/
klh5stk14#
我发现这个查询比第一个更有用。它省略了额外的字符、数字和符号,所以它只会计算一段文字中的单词。