PostgreSQL,GROUP BY和Window函数

时间:2019-04-24 13:11:55

标签: sql postgresql

我在PostgreSQL中得到以下查询,该查询可以显示记录:

'SELECT TO_CHAR(date_trunc(\'hour\', time::timestamp), \'YYYY-MM-DD HH24:MI:SS\') AS time_from,
        TO_CHAR(date_trunc(\'hour\', time::timestamp) + interval \'1 hour\', \'YYYY-MM-DD HH24:MI:SS\') AS time_to,
        SUM(km) AS km
 FROM cars 
 GROUP BY date_trunc(\'hour\', time::timestamp) LIMIT 1000 OFFSET 50'

我想添加SUM(km) OVER() as km_total来获得km的总数,因为查询中有limitoffset

但是然后我得到了错误:

error: column "cars.km" must appear in the GROUP BY clause or be used in an aggregate function

但是我不允许将其添加到我的GROUP BY中,这给了我以下错误:

error: window functions are not allowed in GROUP BY

1 个答案:

答案 0 :(得分:2)

您要

   SUM(SUM(km)) OVER () AS total_km

一开始SUM()的嵌套看起来很奇怪。内部SUM(km)是聚合函数。外部SUM()是窗口函数。