PostgreSQL窗口函数问题:要求GROUP BY

时间:2015-05-06 14:40:13

标签: postgresql

我有一张桌子存放管道以及日期和城市。我需要按城市和安装年份计算管道长度总和和百分比。

以下是我正在寻找的结果:

  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

我用这个脚本构建一个测试表:

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) ; 

为了实现我的查询,我使用窗口函数来计算每个城镇的管道长度总和,如下所示:

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 ;

我收到一条错误消息,要求我将列'长度'添加到GROUP BY子句中,这根本不会给出相同的结果(我不想按长度分组,这将毫无意义)。

任何人都有不同的想法吗?我担心我必须使用WITH mytable AS (...) SELECT ...的临时表。

2 个答案:

答案 0 :(得分:1)

窗口函数在分组后应用,您应该始终使用WINDOW关键字来记住这一点。

你很接近,你只需要总和总和来获得城市总数。

SELECT
  city,
  install_year,
  sum(length) AS length,
  sum(sum(length)) OVER w AS total_by_city,
  (sum(length) * 100) / (sum(sum(length)) OVER w) AS percentage
FROM pipes
GROUP BY city, install_year
WINDOW w AS (PARTITION BY city )
ORDER BY city, install_year DESC;

答案 1 :(得分:0)

我找到了这个:

SELECT DISTINCT
  city,
  install_year,
  sum(length) OVER (PARTITION BY city, install_year) AS length,
  sum(length) OVER (PARTITION BY city, install_year)*100 / sum(length) OVER (PARTITION BY city) AS percentage

FROM pipes

ORDER BY city, install_year DESC ;