coson
coson

Reputation: 8669

T-SQL CASE in WHERE Clause

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?

Upvotes: 1

Views: 1615

Answers (1)

Andomar
Andomar

Reputation: 238296

You could use row_number to number each row by sales, and use a where clause to exclude the 2nd row if it's from this year:

SELECT  TOP 1 *
FROM    (
        SELECT  row_number() over (order by Sales desc) as rn
        ,       *
        FROM    dbo.fnGetDate(181, '08-01-2011') 
        ) as SubQuery
WHERE   (rn >= 2 and datepart(year, getdate()) <> SubQuery.year)
        or rn >= 3
ORDER BY
        rn

Upvotes: 4

Related Questions