简体   繁体   中英

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'.

I have the following query in a prepared statement in my JDBC code:

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. It will always return (only) one row.

If the given timestamp is smallest timestamp in the table, it will return NULL . If the given timestamp doesn't exist in the table, it will return 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

But if run for a nonexistent record myService.getPriorTimestamp("01-MAR-2017") , it returns NULL

If run for the smallest timestamp in the table myService.getPriorTimestamp("01-JAN-2017") , it returns NULL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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