I have a table, it looks something like this:
id year effective price
1 2000 2012-01-01 1000
2 2001 2012-01-01 1100
3 2002 2012-01-01 1200
4 2003 2012-01-01 1300
5 2000 2012-03-01 1500
6 2001 2012-03-01 1600
7 2002 2012-03-01 1700
8 2003 2012-03-01 1800
9 2000 2011-12-01 900
10 2001 2011-12-01 1000
11 2002 2011-12-01 1100
12 2003 2011-12-01 1200
In this table is a bunch of data that contains price histories for a number of items. They are not in any manner of regular order, and it seems that people have randomly gone into the database and made changes. I did not set this database up, nor have I developed the application that inserts and updates the data. My only objective is to present the data specified in the manner my client wants.
That being said, I am having a difficult time getting the information I need. In the above example data, I need to be able to sort the prices and get a distinct number for each specific year. This has to be filtered by the most recent effective date as input by the end user.
For instance, if the user wanted the most recent data (as of today’s date), the response should be something like this:
5 2000 2012-03-01 1500
6 2001 2012-03-01 1600
7 2002 2012-03-01 1700
8 2003 2012-03-01 1800
If the user, on the other hand, wanted the most recent data as of 2012-02-01, then it should return:
1 2000 2012-01-01 1000
2 2001 2012-01-01 1100
3 2002 2012-01-01 1200
4 2003 2012-01-01 1300
My issue lies in not knowing how to build this query. Is it even possible to build this as a single query, or will I have to perform multiple queries in order to get the data? I’d like as small of a footprint as possible, since I have to grab data from four different tables which share years, but have other different data.
I have tried this query to no effect:
select id, year, effective, price
from mytable
group by year
having effective < '2012-02-01'
which gives this result:
1 2000 2012-01-01 1000
2 2001 2012-01-01 1100
3 2002 2012-01-01 1200
4 2003 2012-01-01 1300
I would have thought that this would have given me the right information, as it seems logical.
I tried this query, also to no effect:
select distinct year, id, effective, price
from mytable
group by effective
having effective < '2012-02-01'
which returns this result:
1 2000 2012-01-01 1000
5 2000 2012-03-01 1500
9 2000 2011-12-01 900
This query seems to be completely wrong.
Any suggestions on how to get this to perform the query correctly?
Using a correlated subquery to get the
MAX(effective)peryearand joining against the main table will work, if you filter the date inside the subquery. The idea is that the subquery will return the set of model years and effective date which are the maximum date less than what you specify in theWHEREclause. Those returned columns can be joined back to the main table to pull in the rest of the columns.Example effective 2012-01-01: http://sqlfiddle.com/#!2/05546/4
Example effective 2013-01-01: http://sqlfiddle.com/#!2/05546/5