I'm currently writing code in SQL to add the column in red to the following table:
The logic is the following:
For every row:
- if flag for this row =1 then use date of this row
- if flag for this row =0 then find the latest row (based on date) on which flag was = 1 for the same party and return the date of that row. If no such row exists, return null
I've found a way to do this by joining the table to itself but I would like to avoid doing that as the size of the table is pretty massive.
What I have
select b.*, a.date, from table a left join table b on a.party=b.party where a.flag =1
Someone told me I could use the lag function, the partition over function and a case when to return the value I'm after but I haven't been able to figure it out.
Can someone help? Thank you so much!
4条答案
按热度按时间cpjpxq1n1#
try this
jdgnovmf2#
use
CROSS APPLY()
to obtain the latest row with flag 1gjmwrych3#
Yes it can be done by joining table, if written properly.
@Sahi query is also good and simple.
Since you were asking for
Dynamic LAG()
This query may or may not be very performant,but it certainly worth learning.
Test this with various sample data and tell me for which scenario it do not work. So that I correct my script accordingly.
vsdwdz234#
try this :->