检索PostgreSQL中日期范围内的记录

时间:2019-03-19 23:18:14

标签: sql postgresql date

对于每位客户,我都尝试检索最近submit_date起45天内的记录。

customer  submit_date   salary
      A   2019-12-31   10000
      B   2019-01-01   12000
      A   2017-11-02   11000
      A   2019-03-03   3000
      B   2019-03-04   5500
      C   2019-01-05   6750
      D   2019-02-06   12256
      E   2019-01-07   11345
      F   2019-01-08   12345

2 个答案:

答案 0 :(得分:1)

抢救窗口函数:

SELECT customer, submit_date, salary
FROM (SELECT customer, submit_date, salary,
             max(submit_date) OVER (PARTITION BY customer) AS latest_date
      FROM thetable) AS q
WHERE submit_date >= latest_date - 45;

答案 1 :(得分:0)

我倾向于尝试:

select t.*
from t
where t.submit_date >= (select max(t2.submit_date) - interval '45 day'
                        from t t2
                       );

我认为这可以充分利用(submit_date)上的索引。

如果要相对于每个客户使用此子句,请使用相关子句:

select t.*
from t
where t.submit_date >= (select max(t2.submit_date) - interval '45 day'
                        from t t2
                        where t2.customer = t.customer
                       );

这需要在(customer, submit_date)上建立索引。