Mysql数据分组和正则表达式

标签 mysql

<分区>

我有一张表格,其中代码由我们的提供者在检查患者后记录下来。代码类似于 A11、B99、C68、A12、O87、F76 等。现在我需要创建一个报告,其中对这些代码进行分组和计数。组应类似于 A00-B99、C00-D48、D50-D89 等。我已经研究并发现我可能必须使用 REGEXP,我想尽可能避免使用它。有人可以帮忙说明什么是有效和优化的方法吗?

表格:

 ID  Codes   description
  1  A11     Infection
  2  A01     Intestinal infectious diseases   
  3  H77     Intestinal infectious diseases    
  5  D98     Intestinal infectious diseases      
  6  D98     Intestinal infectious diseases
  7  A11     Intestinal infectious diseases
  8  A00     Intestinal infectious diseases
  9  A03     Intestinal infectious diseases
  10  D00     Intestinal infectious diseases   
11  D98     Intestinal infectious diseases
... 
...
...
...

期望的结果

code_group    Count
A00-B99       10
C00-D48       50
D50-D89       100  
...
...
...

最佳答案

您可以使用 case 语句进行聚合:

select (case when code between 'A00' and 'A99' then 'A00-A99'
             when code between 'B00' and 'C48' then 'B00-C48'
             when code between 'C49' and 'D99' then 'C49-D99'
             . . .
        end) as codeGroup,
       count(*)
from t
group by codeGroup
order by codeGroup;

关于Mysql数据分组和正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33393377/

相关文章:

php - 如果图像字段为空,如何使用php插入数据

php - 从 while 循环向数据库插入多行

php - CodeIgniter:所有 $this->db->query() 方法调用的 SQL 审计?

mysql - 没有列顺序的唯一键约束

PHP 换行 br 与 ENT_QUOTES

php - mysql - 按间隔查询和/或不返回任何内容

mysql - 考虑到目前为止已删除的每周计数

c# - 使用 NHibernate 加密和解密数据

mysql - 使用 MySQL Join 时出现问题

MySQL 限制子句不接受 2 个参数