简体   繁体   English

如何在 postgresql 中按天和组求和值?

[英]How to Sum values by day and group in postgresql?

i have the following table:我有下表:

date日期 value价值 Group团体
2021-04-07 00:00:00 2021-04-07 00:00:00 5 5 a一个
2021-04-07 00:00:00 2021-04-07 00:00:00 10 10 b b
2021-04-07 01:00:00 2021-04-07 01:00:00 5 5 a一个
2021-04-07 01:00:00 2021-04-07 01:00:00 4 4 b b
2021-04-08 00:00:00 2021-04-08 00:00:00 5 5 a一个
2021-04-08 00:00:00 2021-04-08 00:00:00 8 8 b b
2021-04-08 01:00:00 2021-04-08 01:00:00 4 4 a一个
2021-04-08 01:00:00 2021-04-08 01:00:00 5 5 b 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 2021-04-07 10 10 a一个
2021-04-07 2021-04-07 14 14 b b
2021-04-08 2021-04-08 9 9 a一个
2021-04-08 2021-04-08 13 13 b 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并按dategroup将实现此目的。 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 2021-04-07 10 10 a一个
2021-04-07 2021-04-07 14 14 b b
2021-04-08 2021-04-08 9 9 a一个
2021-04-08 2021-04-08 13 13 b b

View on DB Fiddle在 DB Fiddle 上查看

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM