Click here to Skip to main content
15,891,943 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
SQL
DECLARE @TB table (ItemId INT, PriceUpdateDate DATE, Price DECIMAL(18,3))
INSERT INTO @TB VALUES (101,'2018-07-20', 375)
INSERT INTO @TB VALUES (101,'2018-07-25', 390)
INSERT INTO @TB VALUES (101,'2018-08-10', 400)
INSERT INTO @TB VALUES (101,'2018-08-15', 450)
INSERT INTO @TB VALUES (101,'2018-08-17', 300)

INSERT INTO @TB VALUES (102,'2018-07-17', 400)
INSERT INTO @TB VALUES (102,'2018-07-18', 450)
INSERT INTO @TB VALUES (102,'2018-07-19', 300)
INSERT INTO @TB VALUES (102,'2018-08-05', 375)
INSERT INTO @TB VALUES (102,'2018-08-15', 390)


SELECT * FROM @TB


DECLARE @FromDate DATE='2018-08-01',@ToDate DATE='2018-08-31'

select * from @TB where PriceUpdateDate between @FromDate and @ToDate


There are records for the criteria given above which is as per my requirement.But let us suppose there is no record corresponding to @FromDate and @ToDate that we passed.
In that case i want the last updated record i.e. very first record before @FromDate which is '2018-07-25' for ItemId=101 and '2018-07-19' for ItemId=102

What I have tried:

I tried
SQL
DECLARE @FromDate DATE='2018-08-01',@ToDate DATE='2018-08-31'

select * from @TB where PriceUpdateDate between @FromDate and @ToDate
Posted
Updated 22-Aug-18 6:03am
v2

SQL
DECLARE @FromDate DATE='2018/08/01',@ToDate DATE='2018/08/31'

select * from @TB where PriceUpdateDate between @FromDate and @ToDate


not - but /
 
Share this answer
 
Comments
CHill60 22-Aug-18 11:52am    
This doesn't answer the OP's question and there is nothing wrong with using - for dates
You need to know which dates are relevent for each item ...
SQL
DECLARE @m TABLE (ItemId INT, MaxDate DATE)
insert into @m SELECT ItemId, MAX(PriceUpdateDate) FROM @TB WHERE PriceUpdateDate < @FromDate GROUP BY ItemId
and then you can do something if no records are returned from your original query
SQL
if exists (select top 1 * from @TB where PriceUpdateDate between @FromDate and @ToDate)
	select * from @TB where PriceUpdateDate between @FromDate and @ToDate
else
	select T1.* from @TB T1 INNER JOIN @M T2 ON T1.ItemId = T2.ItemId AND T1.PriceUpdateDate = T2.MaxDate
 
Share this answer
 
Comments
xpertzgurtej 23-Aug-18 1:18am    
thanks.. It worked as required..

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