计算一个词在列中出现的次数

Count how many times a word exist in column

我有一个 table 1:

CREATE TABLE table1
INSERT INTO table1 values('XYZ')
INSERT INTO table1 values('ABC')
INSERT INTO table1 values('XYZ~ABC~AAA')
INSERT INTO table1 values('123')

然后,我有字符串'ABC~XYZ~123'。我需要使用 SQL:

将这个字符串拆分成每个单词
Select VALUE FROM STRING_SPLIT('ABC~XYZ~123','~')

return是table2

ABC
XYZ
123

我想统计table2中的每个单词在table1中出现了多少次

预期输出为

ABC|3
XYZ|2
123|1

对此有什么想法吗?

除了评论中的建议外,您还可以使用下面的 Count() 功能。但是以这种格式存储会给您带来提取以及与其他表的连接的困难。

Select T1Value, Count(*) as [NoCount] from(
 Select table1.Value as T1Value, Value FROM STRING_SPLIT('ABC~XYZ~123','~')
 inner join table1 on Value = table1.Value
)a group by T1Value

编辑

CREATE TABLE table1(
  TableValue varchar(max)
);

INSERT INTO table1 (TableValue) values ( 'XYZ');
INSERT INTO table1 ( TableValue) values ( 'ABC');
INSERT INTO table1 ( TableValue) values ( 'XYZ~ABC~AAA');
INSERT INTO table1 ( TableValue) values ( '123~ABC');

SELECT b.value
    ,Count(*)
FROM (
    SELECT VALUE
    FROM STRING_SPLIT('ABC~XYZ~123', '~')
    ) a
INNER JOIN (
    SELECT *
    FROM table1
    CROSS APPLY STRING_SPLIT(TableValue, '~')
    ) b ON a.Value = b.Value
GROUP BY b.Value

这里是给定的Live Demo on db <> fiddle

如果我对你的情况理解正确,下一条语句可能会有所帮助:

文本和table:

DECLARE @text varchar(100) = 'ABC~XYZ~123'
CREATE TABLE Data (
   Id int,
   [Text] varchar(100)
)
INSERT INTO Data
   (Id, [Text])
VALUES
   (1, 'XYZ'),
   (2, 'ABC'),
   (3, 'XYZ~ABC~AAA'),
   (4, '123~ABC')

声明:

SELECT t.[value] AS [Word], j.[Count]
FROM STRING_SPLIT(@text, '~') t
LEFT JOIN (
   SELECT s.[value], COUNT(*) AS [Count]
   FROM Data d
   CROSS APPLY STRING_SPLIT(d.[Text], '~') s
   GROUP BY s.[value]
) j ON t.[value] = j.[value]

结果:

-----------
Word  Count
-----------
ABC   3
XYZ   2
123   1

设置

create table STRINGS (ID int, STRINGS varchar(max));

insert into STRINGS (ID, STRINGS) values (1, 'XYZ');
insert into STRINGS (ID, STRINGS) values (1, 'ABC');
insert into STRINGS (ID, STRINGS) values (1, 'XYZ~ABC~AAA');
insert into STRINGS (ID, STRINGS) values (1, '123~ABC');

declare @VALUES varchar(max) = 'XYZ~ABC~123';

计算:

select V1.VALUE, count(STRINGS.ID) 
from string_split(@VALUES,'~') V1
     cross join STRINGS
     outer apply string_split(STRINGS.STRINGS,'~') V2
where V2.VALUE = V1.VALUE     
group by V1.VALUE     

结果

-----------
Value Num
-----------
ABC   3
XYZ   2
123   1

现场示例: https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=15b95efcf69ea98fafbb7dda1c624551