【问题标题】:Mysql query to count occurrences of names, where they may have trailing characters?Mysql查询来计算名称的出现次数,它们可能有尾随字符?
【发布时间】:2016-12-09 17:39:34
【问题描述】:

我有一个数据库,其中包含大量包含人名的行。但是,名称可能包含尾随数字。

例如,它可能如下所示:

Bob
Mike
Betsy
Bob 2/2
Kevin
Mike 2/3
Mike 3/3

我想运行一个查询,以便计算姓名的数量,但我不确定如何执行此操作,以便将“Mike X/Y”包含在“Mike”的计数中。

例如我的计数是:

Bob = 2
Mike = 3
Betsy = 1
Kevin = 1

这可以用mysql吗?

【问题讨论】:

  • 您的数据似乎存在一些严重问题。你为什么不改一下呢

标签: mysql count


【解决方案1】:

有点笨拙,但您可以尝试使用正则表达式测试数字是否存在,然后使用子字符串获取第一个数字之前的所有内容

select newname, count(*)
from
(
select name,
            case when name REGEXP '[0-9]' = 1 then
            case 
                when locate('0',name) > 0 then substring(name,1,locate('0',name) -2)
                when locate('1',name) > 0 then substring(name,1,locate('1',name) -2)
                when locate('2',name) > 0 then substring(name,1,locate('2',name) -2)
                when locate('3',name) > 0 then substring(name,1,locate('3',name) -2)
                when locate('4',name) > 0 then substring(name,1,locate('4',name) -2)
                when locate('5',name) > 0 then substring(name,1,locate('5',name) -2)
                when locate('6',name) > 0 then substring(name,1,locate('6',name) -2)
                when locate('7',name) > 0 then substring(name,1,locate('7',name) -2)
                when locate('8',name) > 0 then substring(name,1,locate('8',name) -2)
                when locate('9',name) > 0 then substring(name,1,locate('9',name) -2)
            end 
            else name
            end as newname
from t
) s 
group by newname
;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-13
    • 2012-12-18
    • 1970-01-01
    • 2011-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多