首页 > 解决方案 > 如何创建一个选择列并返回不同文本的不同字符串的sql过滤器?

问题描述

我需要选择一列并使其与众不同。

该列是文本类型。

问题是在该列的某些行中添加了超出通常值的字符串,因此我无法过滤数据以区分。

该列包含用户名。例子:

列用户名

username1
username2
username3
{hi my name is username2}
username2
{hi my name is username3}
username4
username5
username2
{hi my name is username2}

一个只做一个不同的查询显然每次出现对我的计数都不同。

select count(distinct username) from table 

我想获得的结果是不同用户名的计数:username1; 用户名2;用户名3;用户名4;用户名5

结果:5

非常感谢大家

标签: sqloracle

解决方案


如果您的示例反映了您的真实数据,它将是这样的:

select count(distinct
  replace(
replace(username,’{hi my name is ’,’’),’}’,’’)
 )
from yourtable

选项 2:

with data as (
  select 'username1' as username union all
  select 'username2' union all
  select 'username3' union all
  select '{hi my name is username2}' union all
  select '{hi my name is username3 and bla bla bla}' union all
  select 'xxxxxxxxxxxx is username6 $$$$$ and bla bla bla}' 
)
select distinct
  substring(
    t1.new_username,
    1,
    case charindex(' ',new_username,0) when 0 then 4000 else charindex(' ',new_username,0) end
    ) as distinct_usernames
from (
  select
    replace(
      substring(
        username,
        charindex('username',username,0),
        4000
      )
     ,'}'
     ,' '
    ) as new_username
  from data
  ) t1

基本上,第二个选项使用子选择来生成始终从用户名开始的字符串,并用{一个空格替换。有了这些数据,主查询会得到一个子字符串,直到找到第一个空格(请记住,如果字符串没有空格,在这种情况下会返回 4000 个字符 - 希望您不会有那么长的用户名 :))。

你可以在这里测试它(dbfiddle


推荐阅读