如何解决PostgreSQL不选择行分组
我有疑问。有一个类似以下示例的构造:(online demo)
您将看到结果的created_at字段。我必须使用查询created_at字段。所以我必须在select created_at中使用它。我不想在select中使用它created_at字段。因为,在存款表中有数百万条记录。我该如何解决这个问题?
(注意:我有很多表要查询,例如“ deposits”表。这只是一个简短的示例。)
create table payment_methods
(
payment_method_id bigserial not null
constraint payment_methods_pkey
primary key
);
create table currencies_of_payment_methods
(
copm_id bigserial not null
constraint currencies_of_payment_methods_pkey
primary key,payment_method_id integer not null
);
create table deposits
(
deposit_id bigserial not null
constraint deposits_pkey
primary key,amount numeric(18,2) not null,copm_id integer not null,created_at timestamp(0)
);
INSERT INTO payment_methods (payment_method_id) VALUES (1);
INSERT INTO payment_methods (payment_method_id) VALUES (2);
INSERT INTO currencies_of_payment_methods (copm_id,payment_method_id) VALUES (1,1);
INSERT INTO deposits (amount,copm_id,created_at) VALUES (100,1,'2020-09-10 08:49:37');
INSERT INTO deposits (amount,created_at) VALUES (200,created_at) VALUES (40,'2020-09-10 08:49:37');
查询:
SELECT payment_methods.payment_method_id,deposit_copm_id.deposit_copm_id,manuel_deposit_amount.manuel_deposit_amount,manuel_deposit_amount.created_at
FROM payment_methods
CROSS JOIN lateral
(
SELECT currencies_of_payment_methods.copm_id AS deposit_copm_id
FROM currencies_of_payment_methods
WHERE currencies_of_payment_methods.payment_method_id = payment_methods.payment_method_id) deposit_copm_id
CROSS JOIN lateral
(
SELECT sum(deposits.amount) AS manuel_deposit_amount,array_agg(deposits.created_at) AS created_at
FROM deposits
WHERE deposits.copm_id = deposit_copm_id.deposit_copm_id) manuel_deposit_amount
WHERE payment_methods.payment_method_id = 1
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。