I have a table storing pipes together with dates and cities. I need to calculate the pipes' length sum and percentage by city and installing year.
Here is the result I'm looking for:
city | install_year | length | percentage
---------+------------------+------------+---------------
A | 2014 | 90 | 32.14
A | 2013 | 70 | 25.00
A | 2012 | 120 | 42.85
B | 2010 | 325 | 100.0
I build a test table with this script:
CREATE TABLE pipes (gid serial NOT NULL, city TEXT, install_year INTEGER, length INTEGER) ;
INSERT INTO pipes (city, install_year, length) VALUES ('A',2014,10), ('A',2014,20), ('A',2014,60), ('A',2013,70), ('A',2012,120), ('B',2010,325) ;
To achieve my query, I use a window function to calculate pipes' length sum for each town, as follow:
SELECT
city,
install_year,
sum(length) AS length,
(sum(length)*100 / sum(length) OVER (PARTITION BY city)) AS percentage
FROM pipes
GROUP BY city, install_year
ORDER BY city, install_year DESC ;
I get an error message asking me to add column 'length' to the GROUP BY clause, which does not give the same result at all (and I do not want to group by length, it would be pointless).
Anyone has an idea to do it differently? I'm afraid I will have to use a temporary table with a WITH mytable AS (...) SELECT ....
sum(length)*100 / sum(length)is always 100 so that's probably not what you want.