PostgreSQL 实现二维数组求和

Postgres数组类型int4[],经常存储24小时数据的时候会用 int4[24]
当需要聚合统计,对每个小时数据求和时就有点麻烦

可以使用下述函数实现求和

CREATE OR REPLACE FUNCTION "public"."final_24hours_group_sum"(IN "v_hours_arr" _int4,  OUT "o_result" _int4)
  RETURNS "pg_catalog"."_int4" AS $BODY$
	
	/*
	* 多个24小时int[],对每小时数据sum
	* @Author Jamin
	* @Example
	* SELECT * FROM public.final_24hours_group_sum(array[[1,2],[10,20]])
	*/
	declare
		tmp  int[];
		v_result int[] := array[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
	BEGIN

   FOREACH tmp SLICE 1 IN ARRAY v_hours_arr
   LOOP
			v_result[1]:=v_result[1]+COALESCE(tmp[1],0);
			v_result[2]:=v_result[2]+COALESCE(tmp[2],0);
			v_result[3]:=v_result[3]+COALESCE(tmp[3],0);
			v_result[4]:=v_result[4]+COALESCE(tmp[4],0);
			v_result[5]:=v_result[5]+COALESCE(tmp[5],0);
			v_result[6]:=v_result[6]+COALESCE(tmp[6],0);
			v_result[7]:=v_result[7]+COALESCE(tmp[7],0);
			v_result[8]:=v_result[8]+COALESCE(tmp[8],0);
			v_result[9]:=v_result[9]+COALESCE(tmp[9],0);
			v_result[10]:=v_result[10]+COALESCE(tmp[10],0);
			v_result[11]:=v_result[11]+COALESCE(tmp[11],0);
			v_result[12]:=v_result[12]+COALESCE(tmp[12],0);
			v_result[13]:=v_result[13]+COALESCE(tmp[13],0);
			v_result[14]:=v_result[14]+COALESCE(tmp[14],0);
			v_result[15]:=v_result[15]+COALESCE(tmp[15],0);
			v_result[16]:=v_result[16]+COALESCE(tmp[16],0);
			v_result[17]:=v_result[17]+COALESCE(tmp[17],0);
			v_result[18]:=v_result[18]+COALESCE(tmp[18],0);
			v_result[19]:=v_result[19]+COALESCE(tmp[19],0);
			v_result[20]:=v_result[20]+COALESCE(tmp[20],0);
			v_result[21]:=v_result[21]+COALESCE(tmp[21],0);
			v_result[22]:=v_result[22]+COALESCE(tmp[22],0);
			v_result[23]:=v_result[23]+COALESCE(tmp[23],0);
			v_result[24]:=v_result[24]+COALESCE(tmp[24],0);
   END LOOP;
	 o_result:=v_result;
	RETURN;
END$BODY$
  LANGUAGE plpgsql IMMUTABLE
  COST 100;
posted @ 2020-07-23 11:06  JaminX86  阅读(1050)  评论(0编辑  收藏  举报