0

我有一张桌子喜欢:

VALID_FROM | VALID_TO   | id | stock
2020-10-01 | 2020-10-02 | 1  | 10
2020-10-02 | 2020-10-04 | 1  | 9
2020-10-04 | 2020-10-08 | 1  | 5
2020-11-12 | 2020-11-26 | 1  | 4
...        | ...        | 1  |
2020-12-15 | 2020-12-16 | 1  | 0

2020-10-01 | 2020-10-02 | 2  | 10
2020-10-02 | 2020-10-04 | 2  | 9
2020-10-04 | 2020-10-08 | 2  | 5
...        | ...        | 2  |
2020-12-15 | 2020-12-16 | 2  | 1

2020-11-12 | 2020-11-26 | 3  | 13
...        | ...        | 3  |
2020-11-30 | 2020-11-30 | 3  | 0

我通过以下方式过滤特定日期范围:

SELECT *
FROM table AS t
WHERE t.VALID_FROM >= ADD_DAYS('2020-11-26', -14)
AND t.VALID_TO <= ADD_DAYS('2020-11-26', +14)

但现在我需要找到在该日期范围内达到“库存”为 0 的每个“id”。

根据该结果,我需要以下条目:

  1. ID
  2. ADD_DAYS('2020-11-26', -14) 日期的库存 - 这里是 '2020-11-12'
  3. 股票跌至0的那一天

所以结束表应该是这样的:

id | stock_at_date-14days | day_of_stock_reaching_0
1  | 4                    | 2020-12-16
3  | 13                   | 2020-11-30

如何使用 SQL 实现这一点?

4

2 回答 2

0

您可以使用join

SELECT t.*, t2.stock as days_before_14
FROM table t LEFT JOIN
     table t2
     ON t.id = t2.id AND
        ADD_DAYS(t.VALID_FROM, -14) >= t2.VALID_FROM AND
        ADD_DAYS(t.VALID_FROM, -14) < t2.VALID_TO AND        
WHERE t.VALID_FROM >= ADD_DAYS('2020-11-26', -14) AND
      t.VALID_TO <= ADD_DAYS('2020-11-26', +14) AND
      t.stock = 0;
于 2020-12-18T14:21:51.693 回答
0

尝试自我加入。

SELECT t.*, t0.*
FROM table AS t
JOIN table AS t0 ON t.id = t0.Id
     AND t.VALID_FROM = ADD_DAYS('2020-11-26', -14)
     AND t0.Stock = 0 
     AND t0.VALID_FROM <= ADD_DAYS('2020-11-26', -14)
     AND t0.VALID_TO <= ADD_DAYS('2020-11-26', +14)
于 2020-12-18T14:00:06.557 回答