简体   繁体   English

JDBC PL / SQL上一行(LAG)仅返回当前值

[英]JDBC PL/SQL Previous Row (LAG) only returning current value

I currently have a table of timestamps with various data and a function that needs to return the prev timestamp based on the given timestamp, 't'. 我目前有一张包含各种数据的时间戳表,以及一个需要根据给定的时间戳“ t”返回上一个时间戳的函数。

I have the following query in a prepared statement in my JDBC code: 我的JDBC代码中的预备语句中有以下查询:

String query = "SELECT LAG(?,1) OVER (ORDER BY TIME_STAMP DESC) FROM " + TABLE;

preparedStatement.setTimestamp(1, t); 

The resultset is simply the same timestamp of my parameter, and there are as many as there are rows in my database. 结果集与参数的时间戳完全相同,数据库中的行数与之相同。

What can i do to return the PREVIOUS timestamp? 我该怎么做才能返回上一个时间戳?

If you are looking to just get the last timestamp before a given timestamp, the below example just using MAX should work. 如果您只想获取给定时间戳记之前的最后一个时间戳记,则下面的示例仅使用MAX It will always return (only) one row. 它将总是(仅)返回一行。

If the given timestamp is smallest timestamp in the table, it will return NULL . 如果给定的时间戳是表中的最小时间戳,则它将返回NULL If the given timestamp doesn't exist in the table, it will return NULL . 如果表中不存在给定的时间戳,它将返回NULL

Create a test table: 创建一个测试表:

CREATE TABLE TIME_STAMP_EVENT(
  EVENT_ID NUMBER,
  TIME_STAMP TIMESTAMP
);

And populate it: 并填充它:

INSERT INTO TIME_STAMP_EVENT VALUES (1,TIMESTAMP '2017-01-01 00:00:00');
INSERT INTO TIME_STAMP_EVENT VALUES (2,TIMESTAMP '2017-02-01 00:00:00');
INSERT INTO TIME_STAMP_EVENT VALUES (3,TIMESTAMP '2017-03-01 00:00:00');
INSERT INTO TIME_STAMP_EVENT VALUES (4,TIMESTAMP '2017-04-01 00:00:00');

Then create the hibernate query: 然后创建休眠查询:

public Timestamp getPriorTimestamp(final Session session, final String testDateText) throws ParseException {
    final SQLQuery theQuery = session.createSQLQuery(
            "SELECT MAX(TIME_STAMP) FROM TIME_STAMP_EVENT WHERE TIME_STAMP < :theTimeStamp AND EXISTS (SELECT 1 FROM TIME_STAMP_EVENT SEMI_TIME WHERE SEMI_TIME.TIME_STAMP = :theTimeStamp)");
    return (Timestamp) theQuery.setTimestamp("theTimeStamp",
            (new SimpleDateFormat("dd-MMM-yyyy").parse(testDateText)))
            .uniqueResult();
}

When this is run: myService.getPriorTimestamp("01-MAR-2017") , it returns the last timestamp before 01-MAR-2017, 2017-02-01 00:00:00.0 运行时: myService.getPriorTimestamp("01-MAR-2017") ,它返回01-MAR- 2017-02-01 00:00:00.0之前的最后一个时间戳。

But if run for a nonexistent record myService.getPriorTimestamp("01-MAR-2017") , it returns NULL 但是,如果为不存在的记录myService.getPriorTimestamp("01-MAR-2017") ,它将返回NULL

If run for the smallest timestamp in the table myService.getPriorTimestamp("01-JAN-2017") , it returns NULL 如果运行表myService.getPriorTimestamp("01-JAN-2017")最小的时间戳,则返回NULL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM