sql - 如何创建一个选择列并返回不同文本的不同字符串的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
非常感谢大家
解决方案
如果您的示例反映了您的真实数据,它将是这样的:
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)
推荐阅读
- ios - Apple 在向我们的服务器发送应用内购买请求时使用哪种国家代码格式?
- javascript - js es6 类注册
- java - 允许无效调用的返回语句
- postgresql - Postgres - 使用 3 + 列和 to_tsvector 创建全文搜索索引
- c++ - 英特尔编译器无法识别来自 gcc 的 avxintrin.h 的标识符
- protractor - 有没有办法在量角器脚本中运行备用“it”块?如果我们能做到,那么怎么做?
- php - $ Composer 找不到 mongodb 扩展,需要 Mongodb 扩展
- android - 如何为 Lua 的 VM/编译器重新编译已编译的字节码列表?
- spring - Spring reactive - 如何在调用方法中处理 mono.error
- python - keras模型H5在理论上是如何工作的