简体   繁体   中英

SQL - Compare current row date value with ALL previous rows dates

Assume I have an End Date in a table

End Date
1/1/2018
5/1/2017
6/1/2017
12/31/2020

I need to compare each row's date with all previous rows date and set a flag or value if the current row date is less than any of the previous rows dates

In this case, row number 3 is greater than row number 2 but it is less than row number 1. Also row number 2 is less than row number 1. Row number 4 is greater than all the other rows

So the result should be something like this

End Date    Flag
1/1/2018     NULL ( Since no previous values to compare)
5/1/2017     Y
6/1/2017     Y
12/31/2020   N

I tried ROWNUMBER and LAG, I was only able to compare just the previous row. Not ALL the previous rows in the table. Please advise

I tried ROWNUMBER and LAG

This means your DBMS supports Windowed Aggregates , now you just need something to ORDER BY to get the order shown in your example:

case -- Since no previous values to compare
  when max(datecol)
       over (order by ????
             rows bweteen unbounded preceding and 1 preceding) is null
  then NULL

  --current row date is less than any of the previous rows dates
  when datecol 
     < max(datecol)
       over (order by ????
             rows bweteen unbounded preceding and 1 preceding)
     then 'Y'
     else 'N' 
  end

Try using correlated subqueries.

SELECT *
,CASE WHEN YT.Column_you_want_compared < (SELECT MIN(Column_you_want_compared) FROM YourTable where Order_column < YT.Order_column ) 
      THEN 1 
      ELSE 0
 END as Flag
FROM YourTable YT

This approach will work if you have a column you can logically order your data with. Otherwise previous rows has no meaning.

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