我在使用 SQL 对带有分隔符的行中的值进行计数时遇到问题

I am having Issues counting values in a row with separators using SQL

我是 snowflake 的新手,正在尝试使用 SQL 计算带有分隔符的行中值的数量。我不知道该怎么做。我用谷歌搜索了解决方案,但没能找到。

table 姓名:Lee_tab

user names
id01 Jon;karl;lee;
id02 Abi;jackson;
id03 don;
id04

我想达到的目标

user names name_count
id01 Jon;karl;lee; 3
id02 Abi;jackson; 2
id03 don; 1
id04 0

这取决于您使用的数据库,因为有一些不同的 语法中的东西。我使用 SQLite 浏览器做了你的例子,我得到了这样的结果:

SELECT SUM(长度(名称) - 长度(替换(名称, ';', '')) +1) 作为总计数 FROM Lee_tab 其中 id = 用户 ID

据我所知,在 Postgres 中没有 length,只有 len,所以请注意。

我的 query-it 只是一个计算值的公式,用 ; 分隔 要获得结果,您应该了解如何加入。

使用 Snowflake 语法重写 json_stattham 的答案。基本上,我们只是计算字符串中分隔符(分号)的数量并加 1。不需要像 json_stattham 的答案那样使用 SUM() 函数。

with cte as (
    select 'id01' as user, 'Jon;karl;lee' as names union all
    select 'id02' as user, 'Abi;jackson' as names union all
    select 'id03' as user, 'don' as names
)
SELECT user, names, (length(names) - length(replace(names, ';'))) + 1 AS name_count 
FROM cte;

这是一个不同的答案,使用 Snowflake SPLIT_TO_TABLE 函数。此函数在分隔符处拆分字符串,为每个值创建一行,我们将其横向连接回 CTE table,最后我们使用标准 SQL 语法进行计数和分组:

with cte as (
    select 'id01' as user, 'Jon;karl;lee' as names union all
    select 'id02' as user, 'Abi;jackson' as names union all
    select 'id03' as user, 'don' as names
)
select user, names, count(value) as count_names
    from cte, lateral split_to_table(cte.names, ';')
group by user, names;

这是使用 REGEXP_COUNT, SPLIT, ARRAY_SIZE, STRTOK_TO_ARRAY 的三个解决方案(我会使用 REGEXP_COUNT 一个):

SELECT 
    column1, 
    column2,
    regexp_count(column2, ';')+1 as solution_1,
    ARRAY_SIZE(split(column2, ';')) as solution_2,
    ARRAY_SIZE(strtok_to_array(column2, ';')) as solution_3  
FROM VALUES
    ('id01','Jon;karl;lee'),
    ('id02','Abi;jackson'),
    ('id03','don');

这给出了

COLUMN1 COLUMN2 SOLUTION_1 SOLUTION_2 SOLUTION_3
id01 Jon;karl;lee 3 3 3
id02 Abi;jackson 2 2 2
id03 don 1 1 1

这是您查询的答案

select user,names,(len(names) - len(replace(names, ';',''))+1) names_count from Lee_tab;

为了更多的理解检查这个,我已经完成了所有 https://www.db-fiddle.com/f/BQuEjw2pthMDb1z8NTdHv/0