获取最大数据小于当前行中的数据

时间:2017-07-18 00:00:14

标签: sql postgresql

我有一个包含3列的表:IdNumberDate,其中IDNumber一起形成主键。该表如下所示:

    +----+--------+------------------+--+
    | ID | Number | Date             |  |
    +----+--------+------------------+--+
    | 1  | 1234   | 10-12-13 1:05:33 |  |
    +----+--------+------------------+--+
    | 1  | 2314   | 10-12-13 1:10:32 |  |
    +----+--------+------------------+--+
    | 2  | 1234   | 10-13-14 3:04:55 |  |
    +----+--------+------------------+--+
    | 3  | 4312   | 05-12-13 5:05:00 |  |
    +----+--------+------------------+--+
    | 3  | 1234   | 04-13-12 3:12:53 |  |
    +----+--------+------------------+--+
    | 4  | 4312   | 05-12-11 5:05:00 |  |
    +----+--------+------------------+--+

现在,我希望数字的最大日期小于每行的日期,无论ID如何。因此,对于ID = 1和Number = 1234,我希望日期最大值为1234但小于该行中的日期。结果应该是04-13-12 3:12:53。同样,对于ID = 2和Number = 1234,结果应为10-12-13 1:05:33。

所以输出应该如下:

    +----+--------+------------------+------------------+
    | ID | Number | Date             | Prev Date        |
    +----+--------+------------------+------------------+
    | 1  | 1234   | 10-12-13 1:05:33 | 04-13-12 3:12:53 |
    +----+--------+------------------+------------------+
    | 1  | 2314   | 10-12-13 1:10:32 | 10-12-13 1:10:32 |
    +----+--------+------------------+------------------+
    | 2  | 1234   | 10-13-14 3:04:55 | 10-12-13 1:05:33 |
    +----+--------+------------------+------------------+
    | 3  | 4312   | 05-12-13 5:05:00 | 05-12-11 5:05:00 |
    +----+--------+------------------+------------------+
    | 3  | 1234   | 04-13-12 3:12:53 | 04-13-12 3:12:53 |
    +----+--------+------------------+------------------+
    | 4  | 4312   | 05-12-11 5:05:00 | 05-12-11 5:05:00 |
    +----+--------+------------------+------------------+

希望这很清楚。我正在绘制一个完整的空白,我应该如何构建我的查询。感谢。

1 个答案:

答案 0 :(得分:1)

我想你只想要一个累积的最大值:

select t.*,
       max(date) over (partition by id
                       order by date
                       rows between unbounded preceding and 1 preceding
                      ) as prev_date
from t;

编辑:

根据问题中的示例,您可能需要:

select t.*,
       max(date) over (partition by number
                       order by date
                       rows between unbounded preceding and 1 preceding
                      ) as prev_date
from t;