Click here to Skip to main content
15,907,687 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want the previous purchase date (the purchase done just before the p_date that is in the output) of each customer.

The output should look like this.

id merchant amount p_date last_purchase_date
101247 flip 617 05-05-2022 12-04-2022
101248 blinkit 332 25-05-2022 04-04-2022
101249 det 528 27-05-2022 04-04-2022

What I have tried:

query:
select *
from (
select * from last_pur
where p_date between '01-05-2022' and '31-05-2022'
)a
Left Join Last_pur as l on l.id=a.id and l.p_date<a.p_date



This query maps all the previous purchase dates. I just want one done just before the p_date in the output.
Posted
Updated 16-Jul-22 7:39am
Comments
0x01AA 16-Jul-22 11:16am    
If you are looking for something which is just before a limit 'l' it needs to be a 'x' which is smaller than 'l'.
Something like pseudo SQL: 'SELECT TOP 1 FROM abc WHERE abc.TheColumn < 'l' ORDER BY abc.TheColumn DESC'

[Edit]
You can glue your SQL and that mentioned SQL together with 'UNION'. Not nice, but maybe helpful in your case.

[Edit]
The above means then adding a row more, rather than a column only ;)
Iaryan 16-Jul-22 11:27am    
Thnak you. That helped.
0x01AA 16-Jul-22 11:29am    
You are very welcome.

 
Share this answer
 
A little piece of advice...

NEVER use "SELECT *". ALWAYS spell out which columns you want, even if it's all of the columns in the table. With future updates in the code and queries, this will prevent strange errors from showing up in code that used to work fine up until you, or someone else, makes changes to the table columns.
 
Share this answer
 
In case you need something 'in between x and y' and the one just below x I see only that:
SELECT x, y, z FROM abc WHERE abc.x BETWEEN a AND b
UNION 
SELECT TOP 1 x, y, z FROM abc WHERE abc.x < a ORDER BY abc.x DESC
ORDER BY x

I hope it helps.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900