在 PostgreSQL 中解析数值范围
Parse Numeric Ranges in PostgreSQL
我想生成一个包含一些经过解析的数字范围的字符串。
我有一个 table 和一些数据
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"
我到底该怎么做?
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从最内层查询向外一步步分析
我想生成一个包含一些经过解析的数字范围的字符串。
我有一个 table 和一些数据
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"
我到底该怎么做?
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从最内层查询向外一步步分析