PostgreSQL使用多列计算百分比的数字
我对SQL非常陌生,我一直在努力解决一个非常基本的问题。我尝试了几种不同的方法来解决这个问题,但到目前为止没有任何效果 所以在我的表touristdata中有4列:transportType、month、year和count。例如:PostgreSQL使用多列计算百分比的数字,sql,postgresql,group-by,percentage,Sql,Postgresql,Group By,Percentage,我对SQL非常陌生,我一直在努力解决一个非常基本的问题。我尝试了几种不同的方法来解决这个问题,但到目前为止没有任何效果 所以在我的表touristdata中有4列:transportType、month、year和count。例如: Month Year Transport Type Count Nov 1992 Car 100 Nov 1992 Plane 250 Dec 1992 Car
Month Year Transport Type Count
Nov 1992 Car 100
Nov 1992 Plane 250
Dec 1992 Car 200
Dec 1992 Plane 250
Jan 1993 Car 200
Jan 1993 Plane 200
除了我有四种不同的交通工具,还有更多的月份和年份
我想计算多年来每种交通工具的使用百分比。因此,我所期望的输出将大致如下:
Year Transport Type Percentage
1992 Car 37.5%
1992 Plane 62.5%
1993 Car 50%
1993 Plane 50%
我当前的代码如下所示:
WITH t1 as(
select transport, SUM(ncount) AS transportTotal
from touristdata
GROUP BY transport)
SELECT years, touristdata.transport, ROUND(100.0 *(transportTotal/SUM(ncount)))
FROM touristdata, t1
GROUP BY years;
在这种形式下,我得到了错误:
ERROR: column "touristdata.transport" must appear in the GROUP BY clause or be used in an aggregate function
LINE 5: SELECT years, touristdata.transport, ROUND(100.0 *(transpor...
但我知道,通过将touristdata.transport和transportTotal添加到组中也不会起作用。我试着确定一下,结果是每年每种交通类型都有4个条目
我以前没有最终的“按年分组”,我试着用子查询来完成,但我想不出来
如果有人能帮我解决这个问题,我会非常感激的 您可以使用窗口功能执行此操作:
SELECT td.years, td.transport, SUM(ncount),
SUM(ncount) / SUM( 1.0*SUM(ncount) ) OVER (PARTITION BY year) as ratio
FROM touristdata td
GROUP BY td.years, td.transport;