首页 > 代码库 > PostgreSQL中查找最大连续性字段

PostgreSQL中查找最大连续性字段

一、建表

lihao=#create table tb (id int,pid int,name varchar);

lihao=#INSERT INTO tb VALUES (1, 0, ‘广东省‘);

lihao=#INSERT INTO tb VALUES (2, 0, ‘浙江省‘);

lihao=#INSERT INTO tb VALUES (3, 2, ‘衢州市‘);

lihao=#INSERT INTO tb VALUES (4, 2, ‘杭州市‘);

lihao=#INSERT INTO tb VALUES (5, 2, ‘湖州市‘);

lihao=#INSERT INTO tb VALUES (6, 2, ‘嘉兴市‘);

lihao=#INSERT INTO tb VALUES (7, 2, ‘宁波市‘);

lihao=#INSERT INTO tb VALUES (8, 2, ‘绍兴市‘);

lihao=#INSERT INTO tb VALUES (9, 2, ‘台州市‘);

lihao=#INSERT INTO tb VALUES (10, 2, ‘温州市‘);

lihao=#INSERT INTO tb VALUES (11, 2, ‘丽水市‘);

lihao=#INSERT INTO tb VALUES (12, 2, ‘金华市‘);

lihao=#INSERT INTO tb VALUES (13, 2, ‘舟山市‘);

lihao=#INSERT INTO tb VALUES (14, 4, ‘上城区‘);

lihao=#INSERT INTO tb VALUES (15, 4, ‘下城区‘);

lihao=#INSERT INTO tb VALUES (16, 4, ‘拱墅区‘);

lihao=#INSERT INTO tb VALUES (17, 4, ‘余杭区‘);

lihao=#INSERT INTO tb VALUES (18, 11, ‘金东区‘);

lihao=#INSERT INTO tb VALUES (19, 1, ‘广州市‘);

lihao=#INSERT INTO tb VALUES (20, 1, ‘深圳市‘);

lihao=#INSERT INTO tb VALUES (111, 0, ‘111‘);

lihao=#INSERT INTO tb VALUES (222, 1, ‘222‘);

lihao=#INSERT INTO tb VALUES (333, 2, ‘333‘);

lihao=#INSERT INTO tb VALUES (444, 4, ‘444‘);

lihao=#INSERT INTO tb VALUES (555, 11, ‘555‘);

二、SQL语句

lihao=# select distinct(a.pid),array((select b.id from tb b where a.pid = b.pid and exists (select * from tb c where b.id = c.id + 1) order by b.id)) from tb a order by a.pid;
 pid |            array            
-----+-----------------------------
   0 | {2}
   1 | {19,20}
   2 | {3,4,5,6,7,8,9,10,11,12,13}
   4 | {14,15,16,17}
  11 | {18}

lihao=# select distinct(a.pid),array((select b.id from tb b where a.pid = b.pid and not exists (select * from tb c where b.id = c.id + 1) order by b.id)) from tb a order by a.pid;
 pid |  array  
-----+---------
   0 | {1,111}
   1 | {222}
   2 | {333}
   4 | {444}
  11 | {555}

三、shell脚本

#!/bin/bash
counter=`psql -c "select count(*) from (select distinct(pid) from tb) a" | sed -n ‘3p‘`
num=$[$counter + 2]
pid=(`psql -c "select distinct(pid) from tb order by pid" | sed -n ‘3,‘‘‘$num‘‘‘p‘`)
echo "==========="
echo "PID:{ID}"
echo "==========="


for pid in ${pid[*]}
do
  m=`psql -c "select count(*) from tb where pid= $pid" | sed -n ‘3p‘`
  n=$[$m + 2]
  id=(`psql -c "select id from tb where pid=$pid order by id" | sed -n ‘3,‘‘‘$n‘‘‘p‘`)

  for ((a=0;a<$m;a++))
  do
     id1=${id[$a]}
     id2=${id[$[$a+1]]}

     diff=$[$id2 - $id1]     
     if [ $diff != 1 ];then
        id_new=${id[@] /$id1/}
     fi
  done

  echo $pid" : {"${id_new[*]}"}"
done

PostgreSQL中查找最大连续性字段