You could use window functions of your database does support them:
For H2 and SQLite the latest KNIME nodes should already support them.