用于计算表之间多个和的查询

osh3o9ms  于 2021-06-23  发布在  Mysql
关注(0)|答案(3)|浏览(248)

鉴于我有下表的员工:

| name    | company  |
|---------|----------|
| John    | Tesco    |
| Anna    | Tesco    |
| James   | Shopo    |
| Jessica | Salsbury |

以及他们的银行交易:

| seller  | buyer   | money |
|---------|---------|-------|
| John    | James   | 40    |
| James   | Anna    | 20    |
| James   | Jessica | 30    |
| Jessica | James   | 10    |

我想创建一个新表来汇总他们的交易

| company  | incoming | outcoming |
|----------|----------|-----------|
| Tesco    | 20       | 40        |
| Shopo    | 50       | 50        |
| Salsbury | 30       | 10        |

但我正在和 GROUP_BY 子句,能够单独计算传入和传出,但无法在不运行额外的 SELECT 内部 INNER JOIN

zour9fqk

zour9fqk1#

典型的 Case .. When 带聚合的问题,使用:

select e.company, 
       sum(case when e.name = b.buyer then money end ) as incoming,
       sum(case when e.name = b.seller then money end ) as outcoming
  from employees e 
  left outer join bank_transactions b
  on ( e.name in (b.seller, b.buyer ) )
  group by e.company
  order by e.company desc;

  company   incoming    outcoming
   Tesco      20           40
   Shopo      50           50
   Salsbury   30           10

sql fiddle演示

qvtsj1bj

qvtsj1bj2#

我认为解决这类问题的关键是将 transactions 分为传入和传出。它使用 union all . 一旦你做了这些,剩下的就成问题了 join 以及 group by :

with tt as (
      select t.seller as employee, 0 as incoming t.money as outgoing 
      from transactions t
      union all
      select t.buyer as employee, t.money as incoming 0 as outgoing 
      from transactions t
     )
select e.company, sum(incoming) as incoming, sum(outgoing) as outgoing
from tt join
     employees e
     on t.employee = e.name 
group by e.company;
f5emj3cl

f5emj3cl3#

首先让我们了解这个问题。假设您的第一个表是'employees',第二个表是bank\u transactions。卖方和买方都在第二张table上。卖方和买方都是第一表中任何一家公司的雇员。因此,让我们复制第二个表并将其保留为两个,一个用于买家,另一个用于别名为的卖家。
b类银行交易——买家
卖方的银行交易
所以现在混乱解决了,卖家会给他们的公司收入,买家会产生结果(支出)。

select e.company as company,
    sum(s.money) as income,
    sum(b.money) as outcome 
    from
    employees e
    left outer join
    bank_transactions s
    on(e.name=s.seller)
    left outer join
    bank_transactions b
    on(e.name=b.buyer)
    group by e.company

相关问题