PostgreSQL SUM不会返回0行的值

时间:2018-06-09 18:48:28

标签: sql postgresql

我有一个事务表,每个事务都有一个地址字段,它引用地址表中的一行,地址表中的每个地址都有一个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

1 个答案:

答案 0 :(得分:4)

此解决方案显示您想要的内容:

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