查询以计算表之间的多个和

时间:2018-07-22 15:13:58

标签: mysql sql group-by aggregate-functions

鉴于我有以下员工表:

| 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子句中苦苦挣扎,能够单独计算传入和传出,但是却无法建立一个可以同时计算两者的查询,而无需运行其他{{1} } SELECT

3 个答案:

答案 0 :(得分:1)

我认为这类问题的关键是将transactions分为传入和传出两个问题。这使用union all。完成此操作后,剩下的就是joingroup 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;

答案 1 :(得分:1)

一个典型的while true; do case $1 in --one|-o) shift; ONE=$1 ;; --two|-t) shift; TWO=$1 ;; --three|-th) shift; THREE=$1 ;; --) shift; break ;; esac done 问题,具有 Aggregation ,请使用:

Case .. When

SQL Fiddle Demo

答案 2 :(得分:1)

首先让我们了解问题所在。 假设您的第一个表格是“员工”,第二个表格是bank_transactions。 卖方和买方都在第二个表中。买卖双方都是 第一表中的任何一家公司。 因此,让我们复制第二个表,并将其保留为两个,一个供买家使用,另一个供别名的卖方使用。

  1. bank_transactions as b-对于买方
  2. bank_transactions as s –对于卖方

因此现在解决了混乱,卖家将为公司赚钱,而买家会产生结果(支出)。现在代码如下所示。

    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