我有一张表格,我们的供应商在检查完病人后会记录代码。代码看起来像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;

10-06 01:08