我有一个PostgreSQL表,并希望它与案例的分层排序。下面是一个示例:
> Name | Port
> ----------------------------
> Switch1 | GigabitEthernet2/2
> Switch1 | GigabitEthernet1/2
> Switch2 | 1.23
> Switch2 | 1.21
> Switch1 | GigabitEthernet2/1
> Switch1 | GigabitEthernet1/1/3
> Switch1 | FastEthernet1/1/14
> Switch1 | FastEthernet3/0/19
> Switch1 | FastEthernet3/0/20
> Switch2 | Port-Channel3
> Switch1 | GigabitEthernet3/0/4
> Switch1 | GigabitEthernet3/1/3
> Switch1 | FastEthernet3/0/2
> Switch2 | 1.14
> Switch2 | Port-Channel6
排序/排序后,应该是这样的:
> Name | Port
> ----------------------------
> Switch1 | FastEthernet1/1/14
> Switch1 | FastEthernet3/0/2
> Switch1 | FastEthernet3/0/19
> Switch1 | FastEthernet3/0/20
> Switch1 | GigabitEthernet1/2
> Switch1 | GigabitEthernet2/1
> Switch1 | GigabitEthernet2/2
> Switch1 | GigabitEthernet1/1/3
> Switch1 | GigabitEthernet3/0/4
> Switch1 | GigabitEthernet3/1/3
> Switch2 | 1.14
> Switch2 | 1.21
> Switch2 | 1.23
> Switch2 | Port-Channel3
> Switch2 | Port-Channel6
我试着用逐个案例的方式来做一些事情。下面是一个示例:
SELECT device.name, device_port.port
FROM device
JOIN device_port ON device.ip = device_port.ip
ORDER BY CASE WHEN device_port.port like 'Fast%' THEN string_to_array(substr(device_port.port, position('/' in device_port.port)-1 ),'/')::float[]
WHEN device_port.port like 'Gigabit%' THEN string_to_array(substr(device_port.port,16),'/')::float[]
WHEN device_port.port like 'Port-channel%' THEN string_to_array(substr(device_port.port,13),'/')::float[] END;
但在这种方式下,不可能首先按device.name和端口名称对其进行排序。例如,结果将如下所示:
> Name | Port
> ----------------------------
> Switch1 | FastEthernet1/1/14
> Switch1 | GigabitEthernet1/2
> Switch1 | FastEthernet3/0/2
> Switch1 | GigabitEthernet3/0/4
以此类推。
发布于 2016-06-02 00:19:36
@klin:哇,这么简单的代码,几乎可以按预期工作了!非常感谢!不知道这样的正则表达式函数是存在的。
唯一缺少的是将{1.14}分成像{1,14}这样的数组。
当前排序失败,例如在这样的情况下:
> Name | Port
> ------------------
> Switch2 | 1.1
> Switch2 | 1.18
> Switch2 | 1.19
> Switch2 | 1.2
> Switch2 | 1.20
> Switch2 | 1.21
但是应该像这样
> Name | Port
> ------------------
> Switch2 | 1.1
> Switch2 | 1.2
> Switch2 | 1.18
> Switch2 | 1.19
> Switch2 | 1.20
> Switch2 | 1.21
我认为解决方案应该是这样的:
order by
name,
regexp_replace(port, '[0-9/\.]', '', 'g'),
string_to_array(regexp_replace(port, '[A-Za-z\-]', '', 'g'), '/')::float[],
string_to_array(regexp_matches(port, '**finding a . in the string**', **give back full string matching pattern** , 'g'), '.')::float[];
问题:
1)你能帮我构建这个regexp_matches函数,这样当它找到一个点时,它总是返回完整的字符串吗?
2) regexp替换表达式中的'‘是什么意思?它通常应该给出替换模式。
再次感谢您的帮助!
https://stackoverflow.com/questions/37569353
复制相似问题