使用 WIndows 函数分组 - Postgresql

Group by with WIndows Function- Postgresql

我知道,在这里使用 Group by 没有意义。但是我正在试验一些东西并得到一个错误,说列成本应该在 group by 中或在聚合函数中使用。我想了解内部发生了什么以及为什么逻辑不正确。假设我有一个 table :

name | date | category | cost,   
jill  | 2019-04-01 | pen | 10 , 
jill  | 2019-04-01 | pen | 40 , 
jill  | 2019-04-01 | coat | 20 , 
Farida | 2019-03-01 | coat | 25,
Farida | 2019-03-02 | coat | 15

将代码写为:

select
     first_name, cast(o_date as date), sum(cost) over(partition by first_name) as tot 
from tab1
group by 
        1,2;

根据查询,将执行第一个分组依据,这将给出:

Jill | 2019-04-01
Farida | 2019-03-01
Farida | 2019-03-02

然后我们通过计算成本列的总和来压缩行,但是对于 first_name.

的每个分区

我期望输出为

Jill | 2019-04-1 | 50
Farida | 2019-03-01 | 60
Farida | 2019-03-02 |60

代码在没有 group by 子句的情况下工作正常(我已经知道如何去做)。为什么我们不能在这里使用group by?请告知代码不正确的原因是什么?

后跟 OVER 子句的 sum() 不是聚合函数,尽管它与聚合函数同名。

因此,在您的查询中,cost 既不是聚合函数的参数,也不是 GROUP BY 子句中的参数。

但是您可以在聚合函数的 结果 上使用 window(顺便说一句,不是“windows”)函数。

所以以下是允许的。 sum() 首先在 cost 上用作聚合函数, 然后 window 函数 sum() 在其上使用。

SELECT first_name,
       cast(o_date AS date),
       sum(sum(cost)) OVER (PARTITION BY first_name) AS tot 
       FROM tab1
       GROUP BY first_name,
                cast(o_date AS date);

附带说明:我建议不要在 GROUP BY 子句中使用列序号。那太容易搞砸了。更喜欢使用列表达式。