有一个包含几个团队数据的表格,如下所示:
original_dates:
date | team_id | value
---------------------------------
2019-01-01 | 1 | 13
2019-01-01 | 2 | 88
2019-01-02 | 1 | 17
2019-01-02 | 2 | 99
2019-01-03 | 1 | 26
2019-01-03 | 2 | 105
2019-01-04 | 1 | 49
2019-01-04 | 2 | 134
2019-01-04 | 1 | 56
2019-01-04 | 2 | 167
但是,在某个日期,我们希望将该天的值重置为 0,将该 ID 的所有先前日期设置为 0,并从所有后续日期中减去该值,最小值为 0。下表列出了需要重置的日期:
inflection_dates:
date | team_id | value
-----------------------------------
2019-01-02 | 2 | 99
2019-01-03 | 1 | 26
这是我希望实现的结果表:
result:
date | team_id | value
---------------------------------
2019-01-01 | 1 | 0
2019-01-01 | 2 | 0
2019-01-02 | 1 | 0
2019-01-02 | 2 | 0 <- row in inflection_dates (value was 99)
2019-01-03 | 1 | 0 <- row in inflection_dates (value was 26)
2019-01-03 | 2 | 6 (-99)
2019-01-04 | 1 | 23 (-26)
2019-01-04 | 2 | 35 (-99)
2019-01-04 | 1 | 30 (-26)
2019-01-04 | 2 | 68 (-99)
唯一的约束是所有表都是read only
的,所以我只能查询它们而不能修改它们。
有谁知道这是否可能?
使用表的连接和 CASE 表达式来计算新值:
select o.date, o.team_id,
case
when o.date <= i.date then 0
else o.value - i.value
end value
from original_dates o inner join inflection_dates i
on i.team_id = o.team_id
请参阅演示(适用于 MySql,但它是标准 SQL(。
结果:
| date | team_id | value|
| ------------------- | ------- | ---- |
| 2019-01-01 00:00:00 | 1 | 0 |
| 2019-01-01 00:00:00 | 2 | 0 |
| 2019-01-02 00:00:00 | 1 | 0 |
| 2019-01-02 00:00:00 | 2 | 0 |
| 2019-01-03 00:00:00 | 1 | 0 |
| 2019-01-03 00:00:00 | 2 | 6 |
| 2019-01-04 00:00:00 | 1 | 23 |
| 2019-01-04 00:00:00 | 2 | 35 |
| 2019-01-04 00:00:00 | 1 | 30 |
| 2019-01-04 00:00:00 | 2 | 68 |
试试这个:
drop table #tmp
---------------------------------
select '2019-01-01' as date, 1 as team_id, 13 as value into #tmp
union select '2019-01-01', 2, 88
union select '2019-01-02', 1, 17
union select '2019-01-02', 2, 99
union select '2019-01-03', 1, 26
union select '2019-01-03', 2, 105
union select '2019-01-04', 1, 49
union select '2019-01-04', 2, 134
union select '2019-01-04', 1, 56
union select '2019-01-04', 2, 167
drop table #tmpinflection
---------------------------------
select '2019-01-02' as date, 2 as team_id, 99 as value into #tmpinflection
union select '2019-01-03', 1, 26
select a.date, a.team_id,
case when a.date <= b.date then 0
else a.value - b.value end as value
from #tmp a left join #tmpinflection b on a.team_id = b.team_id where b.date is not null