首页 > 解决方案 > 如何对一行 PostgreSQL 中的值求和?

问题描述

我有一个问题,将所有值汇总在一行中。表是这样的:

1

如何像这样对所有值求和?

2

公式是这样的:

column 2019 = 2019,
column 2020 = 2020 + column 2019,
column 2021 = 2021 + column 2020,
column 2022 = 2022 + column 2021,
column total = same as the previous column

我的查询:

SELECT 3 AS id,
    'Equity / Modal'::text AS title,
    COALESCE(sum(a."2019") OVER (ORDER BY a.transaction) , 0::numeric) AS "2019",
    COALESCE(sum(a."2020" + "2019") OVER (ORDER BY a.transaction), 0::numeric) AS "2020",
    COALESCE(sum(a."2021" + "2020") OVER (ORDER BY a.transaction), 0::numeric) AS "2021",
    COALESCE(sum(a."2022" + "2021") OVER (ORDER BY a.transaction), 0::numeric) AS "2022",
    COALESCE(sum("2022") OVER (ORDER BY a.transaction), 0::numeric) AS total
FROM vw_blm_dashboard_iurantransaksi_anggota a
WHERE a.transaction = 'SUBTOTAL';

标签: postgresqlwindow-functions

解决方案


推荐阅读