对数字字符串的数字进行排序

时间:2016-06-30 13:46:25

标签: sql postgresql

我需要 SORT Postgres中某些字符串值的所有数字。

例如,如果我有两个字符串,例如

"70005" ==> "00057"
"70001" ==> "00017"
"32451" ==> "12345"

由于我的逻辑限制,我无法将字符串转换为整数或bigint。有可能这样做吗?

2 个答案:

答案 0 :(得分:1)

使用递归cte。拿第一个字符。 if '0'如果忽略它,则转到target字符串的开头。

然后使用LPAD追加0,直到你得到长度10。

<强> SQL DEMO

WITH RECURSIVE cte (id, source, target) as (
    SELECT 1 as id, '70001' as source , '' as target
    UNION 
    SELECT 2 as id, '70005' as source , '' as target
    UNION ALL
    SELECT id,
         substring(source from 2 for length(source)-1) as source, 
         CASE WHEN substring(source from 1 for 1) = '0' THEN target
              ELSE substring(source from 1 for 1) || target
         END
    FROM cte
    WHERE length(source) > 0
), reverse as (
    SELECT id, 
           target, 
           row_number() over (partition by id 
                              order by length(target) desc) rn
    FROM cte
)
SELECT id, LPAD(target::text, 10, '0')
FROM reverse
WHERE rn = 1

<强>输出

| id |       lpad |
|----|------------|
|  1 | 0000000017 |
|  2 | 0000000057 |

答案 1 :(得分:1)

假设您的数据组织如下:

Table: strings

| id | string  |
|----+---------|
| 1  | '70005' |
| 2  | '70001' |
 etc...

然后你可以使用这样的查询:

SELECT all_digits.id,
       array_to_string(array_agg(all_digits.digit ORDER BY all_digits.digit), '')
FROM (
    SELECT strings.id, digits.digit
    FROM strings, unnest(string_to_array(strings.string, NULL)) digits(digit)
) all_digits
GROUP BY all_digits.id

此查询的作用是将表格拆分为字符串中每个字符的一行,对表格进行排序,然后将字符聚合回字符串。

这里有一个SQL小提琴:http://sqlfiddle.com/#!15/7f7fb0/14