Postgres SQL Join距离最近不到四分之一

时间:2019-02-26 10:58:54

标签: sql postgresql

我有表1

ID | public_date
1  | 1992-06-03
2  | 2000-12-15

表2是一系列范围内的季度结束日期

Date
1995-12-31
1996-03-31
..
..
2000-12-31

我希望结果表为

ID | date        | public_date
1  | 1995-12-31  | 1992-06-03
1  | 1996-03-31  | 1992-06-03
1  | 1996-06-30  | 1992-06-03
      ...
      ...
1  | 2000-12-31  | 2000-12-15

基本上,将公共日期分配给最近的季度结束日期。目前,我有这个查询

SELECT DISTINCT ON (x."date")
       x."date", r.public_date
FROM   quarter_end_series as x
LEFT   JOIN public_time r ON r.public_date <= x."date" 
where x.date >= '1995-12-31 00:00:00'
ORDER  BY x."date", r.outlookdate desc;

但是这个查询花了4个小时,有什么方法可以更有效地做到这一点?

2 个答案:

答案 0 :(得分:1)

尝试子查询:

select pt.*,
       (select qes.date
        from quarter_end_series qes
        where qes.date <= pt.date
        order by qes.date desc
       ) as quarter_end_date
from public_time pt;

quarter_end_series(date)上添加索引。

这节省了对大量数据的排序-这应该使它更具性能。

答案 1 :(得分:0)

我想您的住所每年固定。喜欢:

1995-12-31
1996-03-31
1996-06-30
1996-09-31
1996-12-31
.... and so on

如果是,则只需查找固定季度的最近日期即可。

每年quarter_end_series的日期不同。您可以尝试子查询而不是联接。如下所示:

SELECT DISTINCT ON ("date")
"date", (SELECT r.public_date FROM public_time r ORDER BY abs(date_diff(x."date",r.public_date)) ASC limit 1) as public_date
FROM   quarter_end_series as x
where x.date >= '1995-12-31 00:00:00'
ORDER  BY x."date";