如何在连续日期中查找特定值

时间:2019-02-04 17:44:16

标签: sql ms-access

我需要您的帮助解决一个小问题。

我使用MS ACCESS处理数据库,并且需要解决查询。我的查询询问: 查找CUSTOMER_ID和TRANSC_ID,其中2个连续值(介于200和500之间)在同一个transc_id中。

我解释一下。

我有这种格式的表格:

CUSTOMER_ID    TRANSC_ID    VALUE   VALUE_DATE
51             10           15      29-12-1999
51             10           20      15-07-2000
51             10           35      18-08-2000
51             10           250     30-08-2000
51             10           13      10-09-2000
51             10           450     15-09-2000
51             11           5       15-09-2000
51             11           23      30-09-2000
51             11           490     10-10-2000
51             11           300     12-10-2000
51             11           85      30-10-2000
51             11           98      01-01-2000
53             10           65      15-10-2000
53             10           14      29-12-2000

我只需要

51             11           490     10-10-2000
51             11           300     12-10-2000

因为两个值是连续的(并且两个值分别是> 250和<500)。

如何在MS ACCESS中进行查询以获得此结果?

谢谢。

1 个答案:

答案 0 :(得分:3)

您可以使用相关子查询获取“下一个”和“上一个”值,然后进行比较:

select t.*
from t
where t.value between 200 and 500 and
      ( (select top 1 t2.value
         from t as t2
         where t2.CUSTOMER_ID = t.CUSTOMER_ID and t2.TRANSC_ID = t.TRANSC_ID and
               t2.value_date > t.value_date
         order by t2.value_date
        ) between 200 and 500 or
        (select top 1 t2.value
         from t as t2
         where t2.CUSTOMER_ID = t.CUSTOMER_ID and t2.TRANSC_ID = t.TRANSC_ID and
               t2.value_date < t.value_date
         order by t2.value_date desc
        ) between 200 and 500
       );