且构网

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

查询返回特定值在字符串中出现的次数?

更新时间:2022-01-03 22:11:54

我玩了一会儿,想出了这个 SQL 小提琴

I played around a bit and came up with this SQL fiddle

相关的 SELECT 查询如下所示(虽然需要两次表扫描,但我相信它可以提高效率):

The relevant SELECT query looks like this (requires two table scans though, I'm sure it can be made more efficient):

select C, sum(dbo.CountOccurancesOfString(B, C)) as number
from Tbl_1 join Tbl_2 on 1=1
group by C
order by number desc

EDIT 这是我从 这个答案:

CREATE FUNCTION dbo.CountOccurancesOfString
(
 @searchString nvarchar(max),
 @searchTerm nvarchar(max)
)
RETURNS INT
AS
BEGIN
 return (LEN(@searchString)-LEN(REPLACE(@searchString,@searchTerm,'')))/LEN(@searchTerm)
END