1

我有这样的表:

    CREATE TABLE public."Payments"
(
  user_id integer,
  "1 month later" numeric(19,4),
  "2 months later" numeric(19,4),
  "3 months later" numeric(19,4),
  "4 months later" numeric(19,4),
  "5 months later" numeric(19,4),
  "6 months later" numeric(19,4),
  "7 months later" numeric(19,4),
  "8 months later" numeric(19,4),
  "9 months later" numeric(19,4),
  "10 months later" numeric(19,4),
  "11 months later" numeric(19,4),
  "12 months later" numeric(19,4)

例如,里面有这样的数据:

INSERT INTO "Payments" ("user_id", "1 month later", "2 months later", "3 months later", "4 months later", "5 months later", "6 months later", "7 months later", "8 months later", "9 months later", "10 months later", "11 months later", "12 months later") VALUES (134329, 190, 190, 190, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL);

我需要为每个用户 ID 获取总和,其中有很多。postgres 中是否有任何可以快速完成的功能?

4

1 回答 1

2

这个问题类似于这个 stackoverflow 问题。这是 SUM 聚合函数的简单使用。

如何在Postgres中分组并返回总和行

SELECT user_id, SUM("1 month later") as "1 month later",SUM("2 months later") as "2 months later",SUM("3 months later") as "3 months later",SUM("4 months later") as "4 months later",SUM("5 months later") as "5 months later",SUM("6 months later") as "6 months later",SUM("7 months later") as "7 months later",SUM("8 months later") as "8 months later",SUM("9 months later") as "9 months later",SUM("10 months later") as "10 months later",SUM("11 months later") as "11 months later", SUM("12 months later") as "12 months later"
FROM public.payments
GROUP BY user_id

此外,如果用户想要所有 12 列的总和,则只需添加列。

SELECT user_id, "1 month later" + "2 months later" + "3 months later" + "4 months later" + "5 months later" + "6 months later" + "7 months later" + "8 months later" + "9 months later" + "10 months later" + "11 months later" + "12 months later") as allMonthsLater    FROM public.payments
于 2016-04-15T00:49:58.590 回答