有一个表格,其中包含多个团队的数据,如下所示:
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
,所以我只能查询它们而不能修改它们。
有人知道这是否可能吗?
答案 0 :(得分:1)
结合表和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
请参见demo(用于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 |
答案 1 :(得分:0)
尝试一下:
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