Sara Moradi
Sara Moradi

Reputation: 33

how to compare two dates in same column in SQL

I have to compare tow dates that they are in one column of the table, I need this comparing to find the date before and after the specific date that I need, also I have to show them in the 3 different columns

I wrote this code but it's totally wrong:

CREATE VIEW
AS
SELECT (CASE 
        WHEN T1.BuyDate > T2.BuyDate THEN T1.BuyDate END)
AS PreviousBuyDate, T1.ItemName, T1.BuyDate,  
(CASE 
        WHEN T1.BuyDate > T2.BuyDate THEN T1.BuyDate END)
AS  NextDate
FROM FoodSara_tbl T1 , FoodSara_tbl T2
GO

input:

|ItemName | BuyDate | ItemOrigin |
|---------|---------|------------|
| cake    |2020-10-2| UK         |
| coca    |2020-5-2 | US         |
| cake    |2019-10-6| UK         |
| coca    |2020-12-2| US         |

Output:

|PreviousDate | ItemName | BuyDate |NextDate |
|-------------|----------|---------|---------|
| NULL        |cake      |2019-10-6|2020-10-2|
| NULL        |coca      |2020-5-2 |2020-12-2|
|2019-10-6    |cake      |2020-10-2| NULL    |
| 2020-5-2    |coca      |2020-12-2| NULL    |

PS: I have to make a date be in order.

Upvotes: 1

Views: 1481

Answers (1)

Hasan Fathi
Hasan Fathi

Reputation: 6106

Try this with LAG function:

select LAG(BuyDate,1) OVER (PARTITION BY ItemName ORDER BY BuyDate asc) previous_date 
     , ItemName
     , BuyDate
     , LAG(BuyDate,1) OVER (PARTITION BY ItemName  ORDER BY BuyDate desc) next_date
from FoodSara_tbl

See the final result: sqlfiddle

OR

Use LAG and LEAD function:

select LAG(BuyDate,1) OVER (PARTITION BY ItemName order by BuyDate) previous_date 
     , ItemName
     , BuyDate
     , LEAD(BuyDate,1) OVER (PARTITION BY ItemName order by BuyDate) next_date
from FoodSara_tbl

See the final result; sqlfiddle

Upvotes: 1

Related Questions