sql - sql server 中每个单词在一个字符串中重复多少次?

标签 sql sql-server

我已经声明了一个字符串,如下所示:

Declare @string
Set @string = 'this line is like this because this is repeated these many times in this line'

我试图找出每个单词重复了多少次。我期待这样的结果

Word   Number
this    x times
line    y times
is      z times

等等……

帮我写代码。任何帮助,将不胜感激。提前谢谢你。

编辑:

到目前为止,我已经找到了替换特定字母的数字单词。

这是它的代码

SELECT Len(@string) - Len(Replace(@string, 'x', '')).

任何解释连同提供的代码将不胜感激。谢谢。

最佳答案

;WITH splitString(val) AS       
(
    -- convert the string to xml, seperating the elements by spaces
    SELECT    CAST('<r><i>' + REPLACE(@string,' ','</i><i>') + '</i></r>' AS XML)
)
SELECT  [Key],
        COUNT(*) [WordCount]
FROM    (   -- select all of the values from the xml created in the cte
            SELECT  p.value('.','varchar(100)') AS [Key]
            FROM    splitString
                    CROSS APPLY val.nodes('//i') t (p)) AS t
GROUP BY [Key]

如果你想获得所有技术..

;WITH splitString(val) AS       
(
    -- convert the string to xml, seperating the elements by spaces
    SELECT    CAST('<r><i>' + REPLACE(@string,' ','</i><i>') + '</i></r>' AS XML)
)
SELECT  Word,
        CAST(COUNT(*) AS VARCHAR) 
            + (CASE WHEN COUNT(*) = 1 THEN ' time' ELSE ' times' END) AS  Number
FROM    (   -- select all of the values from the xml created in the cte
            SELECT  p.value('.','varchar(100)') AS Word
            FROM    splitString
                    CROSS APPLY val.nodes('//i') t (p)) AS t
GROUP BY Word

关于sql - sql server 中每个单词在一个字符串中重复多少次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35021638/

相关文章:

c# - EF6 : Modifying an entity property with a foreign key relation - Do I need to change the Id or the related object or both?

sql-server - 如何使用 SQL 从文字中获取变量值?

sql-server - 以步骤格式构建 SQL 表

android - Sqlite:小计在自己的行又名 "rollup"

mysql - 在 MySQL 中重新创建 UNI 和 MUL 索引

mysql - 当 Value 为 NULL 时与/mySQL 合并

sql - 记录 SQL Server 2008 Express 数据库上的所有查询?

sql-server - 将所有存储过程和函数一次从一个 sql server 复制到另一个的最简单方法

sql - Delphi 2007 Adoquery参数不起作用

java - Android 数据库更新不起作用