且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SQL Server 2008中列中出现的所有单词的单词计数

更新时间:2023-02-10 12:18:05

我将使用表值函数拆分字符串,然后在查询中将它们分组.像这样:

I would use a table valued function to split the strings, and then group them in a query. Something like this:

SELECT item, count(1)
FROM ticket_diary_comment 
    CROSS APPLY dbo.fn_SplitString(comment_text, ' ')
GROUP BY item

以及fn_SplitString的定义:

CREATE FUNCTION [dbo].[fn_SplitString]   
(   
    @String VARCHAR(8000),   
    @Delimiter VARCHAR(255)   
)   
RETURNS   
@Results TABLE   
(   
    ID INT IDENTITY(1, 1),   
    Item VARCHAR(8000)   
)   
AS   
BEGIN   
INSERT INTO @Results (Item)   
SELECT SUBSTRING(@String+@Delimiter, num,   
    CHARINDEX(@Delimiter, @String+@Delimiter, num) - num)   
FROM Numbers   
WHERE num <= LEN(REPLACE(@String,' ','|'))   
AND SUBSTRING(@Delimiter + @String,   
            num,   
            LEN(REPLACE(@delimiter,' ','|'))) = @Delimiter   
ORDER BY num RETURN   
END   

此功能需要数字表,其中基本上只是CREATE TABLE Numbers(Num int),并且包含从1到10,000(或更多/更少,取决于需要)的所有数字.如果您的数据库中已经有一个数字表,则可以用该表/列替换现有的表.

This function requires a numbers table, which is basically just CREATE TABLE Numbers(Num int) and contains all the numbers from 1 to 10,000 (or more/less depending on needs). If you already have a numbers table in your DB you can substitute that table/column for what you already have.