Window Function Based on Transition of a Column Value
Question
Source: https://stackoverflow.com/questions/70494696/window-function-based-on-transition-of-a-column-value
I have response query as follows:
dest |
emp |
893106 |
0 |
717205 |
1 |
888305 |
0 |
312301 |
1 |
645100 |
0 |
222001 |
0 |
761104 |
1 |
I want to get window function to separate rows like this:
dest |
emp |
893106 |
0 |
717205 |
1 |
dest |
emp |
888305 |
0 |
312301 |
1 |
dest |
emp |
645100 |
0 |
222001 |
0 |
761104 |
1 |
So, each window has to begin with emp value = 0 and end with emp value = 1. It has to detect a transition of a column value.
Answer
For such a scenario where data is ordered by a certain field, you create a new group whenever the emp value of the previous record is 1. It is complicated to implement the process in SQL. You need to create row numbers first and the marker column as needed, and perform the grouping according to the marker column and row numbers. A common alternative is to fetch the original data out of the database and process it in Python or SPL. SPL, the open-source Java package, is easier to be integrated into a Java program and generate much simpler code. It does the computation with only two lines of code:
A |
|
1 |
=PG.query("select dest,emp from t3 order by sth") |
2 |
=A1.group@i(emp[-1]==1) |
View SPL source code.
SPL Official Website 👉 https://www.scudata.com
SPL Feedback and Help 👉 https://www.reddit.com/r/esProcSPL
SPL Learning Material 👉 https://c.scudata.com
SPL Source Code and Package 👉 https://github.com/SPLWare/esProc
Discord 👉 https://discord.gg/cFTcUNs7
Youtube 👉 https://www.youtube.com/@esProc_SPL
Chinese version