我的桌子只有一个col,并且包含自由文本,每个关键字用空格分隔
TEXT
apple orange dog
apple banna cat
我希望得到一个像
的结果apple 2
orange 1
dog 1
banna 1
cat 1
只用SQL吗?
答案 0 :(得分:0)
试试这个
创建功能
Create FUNCTION [dbo].[fn_Split](@text varchar(8000), @delimiter varchar(20))
RETURNS @Strings TABLE
(
position int IDENTITY PRIMARY KEY,
value varchar(8000)
)
AS
BEGIN
DECLARE @index int
SET @index = -1
WHILE (LEN(@text) > 0)
BEGIN
SET @index = CHARINDEX(@delimiter , @text)
IF (@index = 0) AND (LEN(@text) > 0)
BEGIN
INSERT INTO @Strings VALUES (@text)
BREAK
END
IF (@index > 1)
BEGIN
INSERT INTO @Strings VALUES (LEFT(@text, @index - 1))
SET @text = RIGHT(@text, (LEN(@text) - @index))
END
ELSE
SET @text = RIGHT(@text, (LEN(@text) - @index))
END
RETURN
END
查询
declare @ColumnNameList VARCHAR(MAX)
select @ColumnNameList = COALESCE(@ColumnNameList +' ' ,'') +column from table
select @ColumnNameList
select value,count(value) as count from (select value from fn_split((select @ColumnNameList),' '))
Space_tbl group by value