我有这样的表:
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获取summ,其中有很多用户ID。 postgres中的任何函数都可以快速完成吗?
答案 0 :(得分:1)
这个问题类似于这个stackoverflow问题。它是SUM聚合函数的简单用法。
how to group by and return sum row in 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