如何计算和列出 SQL 字符串中由分号分隔的短语或单词的出现次数?

How do you count and list number of occurrences of a phrase or word separated by a semicolon in a string in SQL?

我有一列的值格式如引号所示。

"Promotion - External; Outside Hire; Reassignment - External; Promotion - External; Promotion - External; Promotion - External; Promotion - External; Outside Hire; Promotion - External"

如何设置格式以使其显示在使用 SSQL Server 2016 的引号中的结果中?

"6 Promotion - External; 2 Outside Hire; 1 Reassignment - External"

在 MS SQL:

DECLARE @text varchar(max) = 'Promotion - External; Outside Hire; Reassignment - External; Promotion - External; Promotion - External; Promotion - External; Promotion - External; Outside Hire; Promotion - External';

select string_agg(concat(c,' ',v),';') 
from  (
    select count(*) as c, trim(value) v
    from string_split(@text,';')
    group by trim(value)
) x;

输出:

2 Outside Hire;6 Promotion - External;1 Reassignment - External

或者,如果您希望以相同的顺序输出,例如:

6 Promotion - External;2 Outside Hire;1 Reassignment - External

那你可以试试:

select string_agg(concat(c,' ',v),';') within group (order by c desc)
from  (
    select count(*) as c, trim(value) v
    from string_split(@text,';')
    group by trim(value)
) x;

这应该适合你

declare @string as varchar(1000), @result varchar(500)

set @string = '"Promotion - External; Outside Hire; Reassignment - External; Promotion - External; Promotion - External; Promotion - External; Promotion - External; Outside Hire; Promotion - External"'
set @string = stuff(stuff(@string,1,1,''), len(@string)-1,1,'')

;with data as
(
    select rtrim(ltrim(i.value('.', 'varchar(max)'))) string
    from 
    (
        select cast('<M>' + replace(@string, ';', '</M><M>') + '</M>' as xml) as info
    ) as d
    cross apply d.info.nodes ('/M') AS Split(i)
), final_result as
(
    select string, count(string) num
    from data
    group by string
)
select @result = 
concat('"',
        stuff(
                (
                    select concat('; ', cast(num as varchar), ' ', string) 
                    from final_result 
                    order by num desc
                    for xml path('')
                )
            , 1, 2, '')
        , '"')

select @result