標籤:
一、建表
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中尋找最大連續性欄位