在PostgreSQL中解析数字范围

时间:2017-05-25 18:26:02

标签: postgresql gaps-and-islands

我想生成一个包含一些已解析数字范围的字符串。

我有一张包含一些数据的表

b_id,s_id
1,50
1,51
1,53
1,61
1,62
1,63
2,91
2,95
2,96
2,97

在PostgreSQL中只使用SQL,我怎么能产生这个输出:

b_id,s_seqs
1,"50-51,53,61-63"
2,"91,95-97"

我该怎么做?

1 个答案:

答案 0 :(得分:2)

select b_id, string_agg(seq, ',' order by seq_no) as s_seqs
from (
    select 
        b_id, seq_no,
        replace(regexp_replace(string_agg(s_id::text, ','), ',.+,', '-'), ',', '-') seq
    from (
        select 
            b_id, s_id, 
            sum(mark) over w as seq_no
        from (
            select 
                b_id, s_id, 
                (s_id- 1 <> lag(s_id, 1, s_id) over w)::int as mark
            from my_table
            window w as (partition by b_id order by s_id)
            ) s
        window w as (partition by b_id order by s_id)
        ) s
    group by 1, 2
    ) s
group by 1;

Here you can find从最里面的查询到外部的逐步分析。