Question

I've got a situation like this:

Table: FunTable

ItemKey     ItemName     ItemPriceEffectiveDate    ItemPrice
11          ItemA        6/6/2009                  $500
12          ItemA        6/15/2009                 $550
13          ItemA        9/9/2009                  $450
14          ItemB        3/9/2009                  $150
15          ItemB        9/9/2009                  $350

I need to do the following:

Select
  ItemName as ItemDescription,
  (SELECT THE PRICE WITH THE LATEST EFFECTIVE DATE FROM TODAY THROUGH THE PAST)
FROM
  FunTable
GROUP BY
  ItemName

The output should be this:

ItemA $550
ItemB $150

So, effective dates for prices can range from 5 years ago through 5 years from now. I want to select the price that is effective either today or in the past (not in the future! it's not effective yet). It's got to be the "most recent" effective price.

Any thoughts?

Was it helpful?

Solution

Something like this (don't have your names, but you get the idea) ...

WITH A (Row, Price) AS
(
  SELECT Row_Number() OVER (PARTITION BY Item ORDER BY Effective DESC) AS [RN],
         Price FROM Table2
  WHERE Effective <= GETDATE()
)
SELECT * FROM A WHERE A.Row = 1

OTHER TIPS

select ft.ItemName,
       price
from   (select   ItemName,
                 Max(ItemPriceEffectiveDate) as MaxEff
        from     FunTable
        where    ItemPriceEffectiveDate <= GETDATE()
        group by ItemName) as d,
       FunTable as ft
where  d.MaxEff = ft.ItemPriceEffectiveDate; 

Edit: Changed the query to actually work, assuming the price does not change more than once a day.

I don't know the answer off the top of my head, but my guess is that you mean need to use a sub-query, which could make it a very expensive query.

It may be easier to pull all the data in an use code to post-process it yourself.

should work if you do

SELECT ItemName, MAX(ItemPriceEffectiveDate)
FROM FunTable
WHERE ItemPriceEffectiveDate < getDate()
GROUP BY ItemName
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top