I have a table value function that returns a table with 5 columns that are sorted by Sales DESC.
Item.Count..Year...Month....Sales............ID
808.........2010.....7......212282.88........1
699.........2011.....7......179029.45........2
829.........2007.....7......135034.52........3
959.........2005.....7......129611.80........4
861.........2006.....7......104667.57........5
What I am trying to do is to get the 2nd greatest sales value. That I can do. However, the business logic states that if the Year of the 2nd greatest sales value is the same as the current year (2011), then get the next sales value (135034.52).
Here’s what I have:
DECLARE @Sales DECIMAL(14, 2) = 179029.45
SELECT *
FROM dbo.fnGetDate(181, '08-01-2011')
WHERE ID =
CASE WHEN Sales = @Sales AND Year = YEAR(DATEADD(M, -1, '08-01-2011'))
THEN 3 ELSE 2 END
Unfortunately, this doesn’t work the way it should. If I change the value in @Sales, it works (i.e. 179029.44).
Can anyone help out?
You could use
row_numberto number each row by sales, and use awhereclause to exclude the 2nd row if it’s from this year: