然后该过程将数据返回给Laravel。基于此数据图表被构建。
我目前的代码:
CREATE OR REPLACE FUNCTION "public"."test"("meterid" int4, "started" text, "ended" text, "preiod" text)
RETURNS TABLE("_kwh" numeric, "datetime" timestamp) AS $BODY$BEGIN
RETURN QUERY
SELECT kwh, a_datetime
FROM "public"."consumption"
WHERE meter_id = meterid
AND a_datetime
BETWEEN to_timestamp(started, 'YYYY-MM-DD HH24:MI:SS')
AND to_timestamp(ended, 'YYYY-MM-DD HH24:MI:SS');
END$BODY$
LANGUAGE plpgsql VOLATILE
COST 100
ROWS 1000
我正在使用PostgreSQL 10.7。
我想创建一个存储过程或函数,该存储过程或函数将根据步骤(天,月,年)返回该期间的列值的总和。例如,我有消费数据表。它...
postgres=# create table consumption (kwh int, datetime date);
CREATE TABLE
postgres=# insert into consumption values (10, 2019-01-01);
ERROR: column "datetime" is of type date but expression is of type integer
postgres=# insert into consumption values (10, '2019-01-01');
INSERT 0 1
postgres=# insert into consumption values (2, '2019-01-03');
INSERT 0 1
postgres=# insert into consumption values (24, '2019-03-06');
INSERT 0 1
postgres=# insert into consumption values (30, '2019-03-22');
INSERT 0 1
并通过generate_series()
进行选择
postgres=# SELECT COALESCE(SUM(kwh), 0) AS kwh,
period::DATE
FROM GENERATE_SERIES('2019-01-01','2019-12-31', '1 day'::interval) AS period
LEFT JOIN consumption ON period::DATE=datetime::DATE
GROUP BY 2
kwh | period
-----+------------
0 | 2019-04-17
0 | 2019-05-29
....
0 | 2019-04-06
0 | 2019-04-26
2 | 2019-01-03
0 | 2019-03-15
...
0 | 2019-11-21
0 | 2019-07-24
30 | 2019-03-22
0 | 2019-05-22
0 | 2019-11-19
...