I have a query with sums I'd like to repeat with variables which are day
and consumption_sector.name
. I don't know how to simplify my question enough not to lose the point I need. Programatically I'd like to have variables and a loop all into one only select result.
Where I am is with having one result line, I'd like to customize and do multiple for having for example all month of year of give date, or all results for a given date for multiple consumption_sector.name
Result
Query I reached
set search_path to dev;
SELECT
(SELECT SUM(total)
FROM daily_unit_big_int
INNER JOIN measuring_point on measuring_point.id = daily_unit_big_int.measuring_point_id
INNER JOIN consumption_sector on consumption_sector.id = measuring_point.consumption_sector_id
WHERE
measuring_point.type='devices_logger' AND -- an enumerate
consumption_sector.name like '%gnacio%' AND
day = '2020-10-25') AS daily_total, -- a date I'd like to give as parameter/variable
(SELECT SUM(total)
FROM daily_unit_big_int
INNER JOIN measuring_point ON measuring_point.id = daily_unit_big_int.measuring_point_id
INNER JOIN consumption_sector ON consumption_sector.id = measuring_point.consumption_sector_id
WHERE
measuring_point.type='devices_logger' AND
consumption_sector.name like '%gnacio%' AND
EXTRACT(MONTH FROM day) = '10' AND
EXTRACT(YEAR FROM day) = '2020'
) AS monthly_total,
(SELECT SUM(total)
FROM daily_unit_big_int
INNER JOIN measuring_point ON measuring_point.id = daily_unit_big_int.measuring_point_id
INNER JOIN consumption_sector ON consumption_sector.id = measuring_point.consumption_sector_id
WHERE
measuring_point.type='devices_logger' AND
consumption_sector.name like '%gnacio%' AND
EXTRACT(YEAR FROM day) = '2020'
) AS yearly_total
;
Minimal example with pseudo code to understand the point
$variable_date='2020-10-25'
for $consumption_sector_id in (12,13,46,72) do
SELECT consumption_sector.id AS consumption_sector_id, SUM(total) AS daily_total
FROM daily_unit_big_int
INNER JOIN measuring_point on measuring_point.id = daily_unit_big_int.measuring_point_id
INNER JOIN consumption_sector on consumption_sector.id = measuring_point.consumption_sector_id
WHERE
measuring_point.type='devices_logger' AND -- an enumerate
consumption_sector.id = $consumption_sector_id AND
day = $variable_date -- a date I'd like to give as parameter/variable
end--for
Result
|consumption_sector_id|daily_total|
|12|100|
|13|1000|
|46|1000|
|72|15468|
Here a fiddle for the example where I retreive all data for a particular day
and a particular consumption_sector_id