Reputation: 30865
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?
Upvotes: 1
Views: 1217
Reputation: 229234
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.
Upvotes: 2
Reputation: 45127
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
Upvotes: 2
Reputation: 10865
should work if you do
SELECT ItemName, MAX(ItemPriceEffectiveDate)
FROM FunTable
WHERE ItemPriceEffectiveDate < getDate()
GROUP BY ItemName
Upvotes: 0
Reputation: 16871
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.
Upvotes: 0