使用条件分组依据创建新列

时间:2020-03-13 09:26:37

标签: sql postgresql

我试图找出一种根据条件求和的方法,即使用汇总值创建新列。

enter image description here

我需要基于列A,B和C的列条件对列D求和。列A中的值1是例外。所需的输出如下-

enter image description here

在其中创建新列E的情况下,该列将根据行1中的列A(10,12)和列B(20)以及列C(3)的条件将列D(2958673 + 2166646)相加。 (1799504)在第2行的A(12)列,B(20)列和C(4)列的条件下

1 个答案:

答案 0 :(得分:1)

这也许是一条评论,但是太长了。

我只是不遵循您要实现的逻辑。您的结果可以通过带有过滤的简单查询生成:

select a, b, c, d as d, d as e
from t
where a = 1;

编辑:

也许这就是您想要的?

select 1, b, c,
       sum(d) filter (where a = 1) as d,
       sum(d) filter (where a in (10, 12)) as e
from t
group by b, c;
相关问题