[英]How to Sum values by day and group in postgresql?
i have the following table:我有下表:
date![]() |
value![]() |
Group![]() |
---|---|---|
2021-04-07 00:00:00 ![]() |
5 ![]() |
a![]() |
2021-04-07 00:00:00 ![]() |
10 ![]() |
b ![]() |
2021-04-07 01:00:00 ![]() |
5 ![]() |
a![]() |
2021-04-07 01:00:00 ![]() |
4 ![]() |
b ![]() |
2021-04-08 00:00:00 ![]() |
5 ![]() |
a![]() |
2021-04-08 00:00:00 ![]() |
8 ![]() |
b ![]() |
2021-04-08 01:00:00 ![]() |
4 ![]() |
a![]() |
2021-04-08 01:00:00 ![]() |
5 ![]() |
b ![]() |
And i want to know how could i sum the values by day and group, like this:我想知道如何按天和组对值求和,如下所示:
date![]() |
total_value![]() |
Group![]() |
---|---|---|
2021-04-07 ![]() |
10 ![]() |
a![]() |
2021-04-07 ![]() |
14 ![]() |
b ![]() |
2021-04-08 ![]() |
9 ![]() |
a![]() |
2021-04-08 ![]() |
13 ![]() |
b ![]() |
Hope someone can help me with this, thanks in advance.希望有人可以帮助我,在此先感谢。
Using the aggregate function sum
and grouping by date
and group
will achieve this.使用聚合 function
sum
并按date
和group
将实现此目的。 Since you have timestamp data, the solution below casts it to a date
type and groups using that.由于您有时间戳数据,因此下面的解决方案将其转换为
date
类型并使用它进行分组。 Finally in the projection, I also casted to a text
to remove the additional date information and just provide with YYYY-MM-DD
最后在投影中,我还转换为
text
以删除附加的日期信息,并仅提供YYYY-MM-DD
Schema (PostgreSQL v11)架构 (PostgreSQL v11)
CREATE TABLE my_table (
"date" TIMESTAMP,
"value" INTEGER,
"Group" VARCHAR(1)
);
INSERT INTO my_table
("date", "value", "Group")
VALUES
('2021-04-07 00:00:00', '5', 'a'),
('2021-04-07 00:00:00', '10', 'b'),
('2021-04-07 01:00:00', '5', 'a'),
('2021-04-07 01:00:00', '4', 'b'),
('2021-04-08 00:00:00', '5', 'a'),
('2021-04-08 00:00:00', '8', 'b'),
('2021-04-08 01:00:00', '4', 'a'),
('2021-04-08 01:00:00', '5', 'b');
Query #1查询 #1
select
"date"::date::text,
sum(value) as total_value,
"Group"
FROM
my_table
GROUP BY
"date"::date, "Group";
date![]() |
total_value![]() |
Group![]() |
---|---|---|
2021-04-07 ![]() |
10 ![]() |
a![]() |
2021-04-07 ![]() |
14 ![]() |
b ![]() |
2021-04-08 ![]() |
9 ![]() |
a![]() |
2021-04-08 ![]() |
13 ![]() |
b ![]() |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.