gpt4 book ai didi

sql - PostgreSQL SUM 不返回 0 行的值

转载 作者:行者123 更新时间:2023-11-29 11:58:21 25 4
gpt4 key购买 nike

我有一个交易表,每个交易都有一个地址字段,它引用地址表中的一行,地址表中的每个地址都有一个 coinID。

我想获得特定用户的每个硬币的所有交易总和。

我遇到的问题是,如果用户有 0 个属于特定硬币的交易或地址,则结果中完全没有。我需要硬币表中所有具有 0 个交易或地址的硬币以总和为 0 返回。

SELECT coins.name, SUM(transactions.amount),coins.price_usd
FROM coins
LEFT JOIN addresses ON addresses.coin_id = coins.id
LEFT JOIN transactions ON transactions.address = addresses.address
LEFT JOIN users ON transactions.user_id = users.id
WHERE users.email = 'testemail@email.com'
GROUP BY coins.name, coins.price_usd

最佳答案

此解决方案向您展示了您想要的:

create table coins (
id int,
name varchar(10),
price_usd int
);

insert into coins (id, name, price_usd) values (1, 'Pound', 2);
insert into coins (id, name, price_usd) values (2, 'Yen', 98);
insert into coins (id, name, price_usd) values (3, 'Euro', 3);

create table addresses (
coin_id int,
address int
);

insert into addresses (coin_id, address) values (1, 20);
insert into addresses (coin_id, address) values (3, 30);

create table transactions (
address int,
user_id int,
amount int
);

insert into transactions (address, user_id, amount) values (20, 500, 123);
insert into transactions (address, user_id, amount) values (20, 500, 101);
insert into transactions (address, user_id, amount) values (30, 501, 456);

create table users (
id int,
email varchar(50)
);

insert into users (id, email) values (500, 'testemail@email.com');
insert into users (id, email) values (501, 'another@email.com');

select coins.name, sum(transactions.amount),coins.price_usd
from coins
join addresses on addresses.coin_id = coins.id
join transactions on transactions.address = addresses.address
join users on transactions.user_id = users.id
where users.email = 'testemail@email.com'
group by coins.name, coins.price_usd
union all
select name, 0, 0
from coins
where id not in (
select coin_id
from addresses
join transactions on transactions.address = addresses.address
join users on transactions.user_id = users.id
where users.email = 'testemail@email.com'
);

结果:

name   sum  price_usd
----- --- ---------
Pound 224 2 -- the requested user
Yen 0 0 -- another user
Euro 0 0 -- coin with no transactions

关于sql - PostgreSQL SUM 不返回 0 行的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50777492/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com