Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate daily sums in PostgreSQL

Tags:

postgresql

sum

I am fairly new in postgres and what am trying to do is calculate sum values for each day for every month (i.e daily sum values). Based on scattering information I came up with something like this:

CREATE OR REPLACE FUNCTION sumvalues() RETURNS double precision AS
$BODY$
BEGIN
   FOR i IN 0..31 LOOP
   SELECT SUM("Energy") 
   FROM "public"."EnergyWh" e
   WHERE  e."DateTime" = day('01-01-2005 00:00:00'+ INTERVAL 'i' DAY);
   END LOOP;

END
$BODY$
LANGUAGE plpgsql VOLATILE NOT LEAKPROOF;
ALTER FUNCTION public.sumvalues()
  OWNER TO postgres;

The query returned successfully, so I thought I had made it. However when am trying to insert the values of the function to a table (which maybe wrong):

INSERT INTO "SumValues"
("EnergyDC") 

    (
     SELECT sumvalues()
     ); 

I get this:

ERROR: invalid input syntax for type interval: "01-01-2005 00:00:00" LINE 3: WHERE e."DateTime" = day('01-01-2005 00:00:00'+ INTERVAL...

I tried to debug it myself but yet am not sure, which of the two I am doing wrong (or both) and why.

Here is an example of EnergyWh

(am using systemid and datetime as composite PK, but that should not matter)

like image 845
Elena_K Avatar asked Dec 08 '25 03:12

Elena_K


1 Answers

see GROUP BY clause http://www.postgresql.org/docs/9.2/static/tutorial-agg.html

SELECT EXTRACT(day FROM e."DateTime"), EXTRACT(month FROM e."DateTime"), 
       EXTRACT(year FROM e."DateTime"), sum("Energy")
   FROM "public"."EnergyWh" e
  GROUP BY 1,2,3

but following query should to work too:

SELECT e."DateTime"::date, sum("Energy")
   FROM "public"."EnergyWh" e
  GROUP BY 1

I am using a short syntax for GROUP BY ~ GROUP BY 1 .. group by first column.

like image 66
Pavel Stehule Avatar answered Dec 10 '25 23:12

Pavel Stehule



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!