我有两张这样的桌子 表1
Group ID submit_date
1 153 2011-08-22
1 158 2011-12-02
1 245 2013-02-22
2 325 2014-01-20
2 285 2015-01-22
3 425 2016-04-22
3 655 2017-02-22
表2
ID as_date amount
153 2011-09-01 500
153 2011-10-01 400
153 2011-11-15 350
153 2012-01-25 250
153 2012-02-15 200
158 2012-01-02 10000
158 2013-05-02 8000
325 2014-02-20 5000
325 2014-03-20 4000
325 2014-04-20 3000
表2中表1的每个id有多个记录。我想查找表1中每个ID的总金额。到期总金额等于当前ID之前提交的同一组中所有ID的总金额。只有在as_date更新且仍然少于提交日期时才应使用到期金额。
示例:
ID 245:组1中有两个ID已在此ID之前提交。 到期金额应为200 + 10000:
153 2012-02-15 200
158 2012-01-02 10000
as_of_date在ID 245提交日期(2013-02-22)之前
结果
Group ID submit_date Total_due_so_far
1 153 2011-08-22 0
1 158 2011-12-02 350
1 245 2013-02-22 10000+200
2 325 2014-01-20 0 (no ID submitted before for Group 2)
2 285 2015-01-22 3000
3 425 2016-04-22 0 (no ID submitted before for Group 3)
3 655 2017-02-22 0 (no ID submitted before for Group 3)
答案 0 :(得分:2)
到目前为止,MySql不支持分析函数,因此必须创建纯SQL中的怪物查询。它不会很快:
| group | id | submit_date | Total_due_so_far |
|-------|-----|----------------------|------------------|
| 1 | 153 | 2011-08-22T00:00:00Z | 0 |
| 1 | 158 | 2011-12-02T00:00:00Z | 350 |
| 1 | 245 | 2013-02-22T00:00:00Z | 10200 |
| 2 | 285 | 2015-01-22T00:00:00Z | 3000 |
| 2 | 325 | 2014-01-20T00:00:00Z | 0 |
| 3 | 425 | 2016-04-22T00:00:00Z | 0 |
| 3 | 655 | 2017-02-22T00:00:00Z | 0 |
演示:http://sqlfiddle.com/#!9/e130e/38
DECLARE @Xml XML = '<MetaData type="Contracts">
<Data column="PositionName">Administrator- Contract Compl</Data>
<Data column="PositionName">Administrator - Contract Compl</Data>
<Data column="PositionName">Dir - Contract Adm & Analytics</Data>
<Data column="PositionName">Director - Commercial Support</Data>
<Data column="PositionName">Lead Contract Admin - Compl</Data>
<Data column="PositionName">Lead Contract Administrator</Data>
<Data column="PositionName">Assoc- Contract Admin</Data>
<Data column="PositionName">Contract Administrator</Data>
<Data column="PositionName">Director- Contract Admin</Data>
<Data column="PositionName">Lead Contract Administrator</Data>
<Data column="PositionName">Manager- Contract Admin</Data>
<Data column="PositionName">Manager - Contract Admin</Data>
<Data column="PositionName">Rep - NGL Distribution</Data>
<Data column="PositionName">Supervisor- Contract Admin</Data>
<Data column="PositionName">VP- Contract Administration</Data>
<Data column="PositionName">Associate Contract Admin</Data>
<Data column="PositionName">Sr Manager - Contract Admin</Data>
<Data column="PositionName">Sr Specialist - Producer Svcs</Data>
<Data column="PositionName">Supervisor - Contract Admin</Data>
<Data column="PositionName">Supervisor - Contract Admin</Data>
<Data column="PositionName">VP - Contract Administration</Data>
</MetaData>';