如何使用 SQL SELECT 根据另一个 table 中的特定行查询 table

How to query table based on specific rows in another table using SQL SELECT

有一个 table 包含几个团队的数据,如下所示:

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。这是一个 table 需要重置的日期:

inflection_dates:

   date    |   team_id   |  value
-----------------------------------
2019-01-02 |      2      |    99
2019-01-03 |      1      |    26

这是我希望实现的结果 table:

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)

唯一的限制就是所有的table都是read only,所以只能查询不能修改。

有谁知道这是否可行?

试试这个:

 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

通过连接表和 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   |