MySql:汇总每个类别和类型的最新银行存款金额
我有四个MySql表(此处简化): 表1:派系(仅供参考) 表2:货币(仅供参考) 表3:事件(仅供参考的列表) 表4:事件银行业务(每次事件后输入的数据,每组每种货币的剩余金额) 注意:派系2没有为事件2存入货币3 我希望能够做到的是,对于每种货币,得到每个派系最后一次存入银行(日期)的总数。(即如果所有派系合并,每种货币目前总共有多少存入银行) 所以,我需要一张看起来像这样的桌子:MySql:汇总每个类别和类型的最新银行存款金额,mysql,group-by,sum,sql-order-by,Mysql,Group By,Sum,Sql Order By,我有四个MySql表(此处简化): 表1:派系(仅供参考) 表2:货币(仅供参考) 表3:事件(仅供参考的列表) 表4:事件银行业务(每次事件后输入的数据,每组每种货币的剩余金额) 注意:派系2没有为事件2存入货币3 我希望能够做到的是,对于每种货币,得到每个派系最后一次存入银行(日期)的总数。(即如果所有派系合并,每种货币目前总共有多少存入银行) 所以,我需要一张看起来像这样的桌子: currency_id | total 1 | 130 (eg 20 + 110)
currency_id | total
1 | 130 (eg 20 + 110)
2 | 190 (eg 50 + 140)
3 | 250 (eg 80 + 170) <- Uses Event 3 for Group 2 as Event 2 doesn't exist
currency_id|总计
1 | 130(如20+110)
2 | 190(如50+140)
3 | 250(如80+170)我想你可以继续这样做:
select eb.currency_id, sum(amount) as total
from events e
inner join (
select faction_id, currency_id, max(date) as md
from event_banking eb
inner join events e
on eb.event_id = e.id
group by faction_id, currency_id
) a
on e.date = a.md
inner join event_banking eb
on e.id = eb.event_id
and a.faction_id = eb.faction_id
and a.currency_id = eb.currency_id
group by currency_id;
这是
id | name | date
1 | Evebt1 | 2013-10-16
2 | Event2 | 2013-10-18 (Note: date out of order)
3 | Event3 | 2013-10-17
id | faction_id | currency_id | event_id | amount
1 | 1 | 1 | 1 | 10
2 | 1 | 1 | 2 | 20
3 | 1 | 1 | 3 | 30
4 | 1 | 2 | 1 | 40
5 | 1 | 2 | 2 | 50
6 | 1 | 2 | 3 | 60
7 | 1 | 3 | 1 | 70
8 | 1 | 3 | 2 | 80
9 | 1 | 3 | 3 | 90
10 | 2 | 1 | 1 | 100
11 | 2 | 1 | 2 | 110
12 | 2 | 1 | 3 | 120
13 | 2 | 2 | 1 | 130
14 | 2 | 2 | 2 | 140
15 | 2 | 2 | 3 | 150
16 | 2 | 3 | 1 | 160
17 | 2 | 3 | 3 | 170
currency_id | total
1 | 130 (eg 20 + 110)
2 | 190 (eg 50 + 140)
3 | 250 (eg 80 + 170) <- Uses Event 3 for Group 2 as Event 2 doesn't exist
select eb.currency_id, sum(amount) as total
from events e
inner join (
select faction_id, currency_id, max(date) as md
from event_banking eb
inner join events e
on eb.event_id = e.id
group by faction_id, currency_id
) a
on e.date = a.md
inner join event_banking eb
on e.id = eb.event_id
and a.faction_id = eb.faction_id
and a.currency_id = eb.currency_id
group by currency_id;