拆分字符串并转换为十进制

时间:2017-03-19 01:34:41

标签: sql postgresql

得到一张包含以下数据的表

输入表

id metric_hex_string
1 '0x8000b0b07007ffff'

hex_string需要拆分为4个组,然后转换为小数,如下所示。在执行此操作时,是否可以对自动列名称进行某种排序?

id metric0 metric1 metric2 metric3
1  32768   45232   28679   65535

1 个答案:

答案 0 :(得分:2)

似乎没有更简单的方法来分割字符串而不是简单的substr()

with my_table(id, metric_hex_string) as (
values (1, '0x8000b0b07007ffff')
)

select id,
    concat('x', substr(metric_hex_string, 3, 4))::bit(16)::int as metric0,
    concat('x', substr(metric_hex_string, 7, 4))::bit(16)::int as metric1,
    concat('x', substr(metric_hex_string, 11, 4))::bit(16)::int as metric2,
    concat('x', substr(metric_hex_string, 15, 4))::bit(16)::int as metric3
from my_table;

 id | metric0 | metric1 | metric2 | metric3 
----+---------+---------+---------+---------
  1 |   32768 |   45232 |   28679 |   65535
(1 row)