SQL 计算以逗号分隔的单词的每次出现次数
SQL Count each occurence of words separated by comma
我在 table 中有一列,单词之间用逗号分隔。我需要计算每个单词的每次出现次数
我的专栏看起来像:('a, b, c'), ('a, b, d'), ('b, c, d'), ('a'), ('a, c');
(fiddle在底部)
这是我得到的:
MyCol Count
-----------------
a 1
a, b, c 3
a, b, d 3
a, c 2
b, c, d 3
但这是我所期望的
MyCol Count
-------------
a 4
b 3
c 3
d 2
这是我到目前为止所做的:
select MyCol, COUNT(*)
from Test
cross apply string_split(MyCol, ',')
group by MyCol
Fiddle : http://sqlfiddle.com/#!18/4e52e/3
请注意单词之间用逗号和 space
分隔
select value,count(*)cntt
from Test
cross apply string_split(MyCol,',')
group by value
order by value;
您使用了错误的列。只需使用 [value]
列(从 STRING_SPLIT()
调用返回)并删除 space 字符(使用 TRIM()
for SQL Server 2017+ 或 LTRIM()
和 RTRIM()
对于早期版本):
SELECT TRIM(s.[value]) AS [value], COUNT(*) AS [count]
FROM Test t
CROSS APPLY STRING_SPLIT(t.MyCol, ',') s
GROUP BY TRIM(s.[value])
ORDER BY TRIM(s.[value])
使用REPLACE
去除白色space,然后使用Subquery
select MyCol,count(MyCol) as Count from(
select
REPLACE (value, ' ', '' ) as MyCol
--TRIM(value) as MyCol -- both TRIM and REPLACE are equivalent
----comment one of them
from test
cross apply string_split(MyCol, ',')) b
group by MyCol
简单:
select MyCol, 1 + LEN(MyCol) - LEN(REPLACE(MyCol, ',', '')) AS NUM
from Test
我在 table 中有一列,单词之间用逗号分隔。我需要计算每个单词的每次出现次数
我的专栏看起来像:('a, b, c'), ('a, b, d'), ('b, c, d'), ('a'), ('a, c');
(fiddle在底部)
这是我得到的:
MyCol Count
-----------------
a 1
a, b, c 3
a, b, d 3
a, c 2
b, c, d 3
但这是我所期望的
MyCol Count
-------------
a 4
b 3
c 3
d 2
这是我到目前为止所做的:
select MyCol, COUNT(*)
from Test
cross apply string_split(MyCol, ',')
group by MyCol
Fiddle : http://sqlfiddle.com/#!18/4e52e/3
请注意单词之间用逗号和 space
分隔select value,count(*)cntt
from Test
cross apply string_split(MyCol,',')
group by value
order by value;
您使用了错误的列。只需使用 [value]
列(从 STRING_SPLIT()
调用返回)并删除 space 字符(使用 TRIM()
for SQL Server 2017+ 或 LTRIM()
和 RTRIM()
对于早期版本):
SELECT TRIM(s.[value]) AS [value], COUNT(*) AS [count]
FROM Test t
CROSS APPLY STRING_SPLIT(t.MyCol, ',') s
GROUP BY TRIM(s.[value])
ORDER BY TRIM(s.[value])
使用REPLACE
去除白色space,然后使用Subquery
select MyCol,count(MyCol) as Count from(
select
REPLACE (value, ' ', '' ) as MyCol
--TRIM(value) as MyCol -- both TRIM and REPLACE are equivalent
----comment one of them
from test
cross apply string_split(MyCol, ',')) b
group by MyCol
简单:
select MyCol, 1 + LEN(MyCol) - LEN(REPLACE(MyCol, ',', '')) AS NUM
from Test