Sql-server – Calculate Return Value – 1,3,6 Month Returns

datesql-server-2008-r2t-sql

How do I calculate the return for 1mth, 3mths, and 6mths?

I have this query but ValuationDate will not be exactly X months ago.

e.g. 2015-01-30 returns 2014-10-30 in the calculation. However, only 2014-10-31 exists in the table. So how do I return the latest date in the table for that month?

SELECT PriceValue FROM @Output WHERE ValuationDate = DATEADD(MONTH,-3,ValuationDate)

ValuationDate is DATETIME. Using SQL Server 2008R2

So in the below table data, I want to return the PriceValue for 2014-10-31 on the row with ValuationDate 2015-01-30

Table Data:

enter image description here

Best Answer

It's still not clear but if you want the value from the first row after the 3-month mark, you can use ORDER BY with TOP 1:

DECLARE @MyValuationDate DATE ; 
SET @MyValuationDate = '20150130' ;

SELECT TOP (1) PriceValue 
FROM @Output 
WHERE  ValuationDate >= DATEADD(MONTH, -3, @MyValuationDate)
ORDER BY ValuationDate ;