Oracle 数据库中的 DISTINCT、SUBSTR 和 MAX

DISTINCT, SUBSTR & MAX in Oracle Database

我有一个如下所示的 table,我想在上面 return 不同的服务器名称,其最大值为 table 中所有排列的最后 4 位数字:

ServerName
APPQTV1234
IISLUG60DF
XCCPTV401D

所以基本上我可以使用以下查询获得唯一组合:

select DISTINCT SUBSTR(ServerName,1,6) from MYTABLE;

这给了我:

ServerName
APPQTV
IISLUG
XCCPTV

现在我想查询 return 最后 4 位数字的最大值,这些数字基本上是十六进制增量

任何建议都会有所帮助!提前致谢

编辑 1 预期结果如下:

所以如果 table 有这些值:

ServerName
APPQTV1234
IISLUG6578
XCCPTV7894
APPQTV4321
IISLUG9999
XCCPTV8049

然后查询应该 return 每个组合的最大值。例如:

ServerName
APPQTV4321
IISLUG9999
XCCPTV8049

我们可以使用 'XX' 格式掩码和 to_number() 将十六进制转换为十进制。 X 的数量必须与十六进制字符串中的字符数匹配。然后就是简单的聚合了。

with mytable as (
select 'APPQTV1234' as servername from dual union all
select 'APPQTV1C34' as servername from dual union all
select 'IISLUG60DF' as servername from dual union all
select 'IISLUG80DF' as servername from dual union all
select 'XCCPTV401D' as servername from dual 
)
select SUBSTR(ServerName,1,6) as server_name
      ,max(to_number(substr(servername, 7, 4), 'xxxx')) as server_no
from MYTABLE
group by SUBSTR(ServerName,1,6)

替代解决方案:如果您的 NLS_SORT 参数设置为 binary(即按 ASCII 值排序),字母数字排序规则将按递增值对十六进制数字进行排序。所以你可以这样做:

with mytable as (
select 'APPQTV1234' as servername from dual union all
select 'APPQTVA234' as servername from dual union all
select 'APPQTV1C34' as servername from dual union all
select 'IISLUG6578' as servername from dual union all
select 'IISLUG80DF' as servername from dual union all
select 'APPQTV4321' as servername from dual union all
select 'IISLUG9999' as servername from dual union all
select 'XCCPTV8049' as servername from dual union all
select 'XCCPTV401D' as servername from dual 
)
select SUBSTR(ServerName,1,6)                           
       || max(substr(servername, 7, 4)) as max_server_name
from MYTABLE
group by SUBSTR(ServerName,1,6)

演示 db<>fiddle