I am not very familiar with SQL and I hope some expert here can show me suitable and efficient query for what I want to achieve. I am using DB2 by the way.
Below is a screenshot of a sample data. What I need is for a given year, select the record with distinct ID1+ID2+Name columns and maximum (most recent) effective date (in YYYYMMDD format, stored as integer), with the above year being in between YearFrom and YearTo range.
FOr anyone that cant see a screenshot:
NAME YearFrom YearTo ID1 ID2 EffDate
item1 2002 2005 AB 10 20091201
item1 2009 2013 AB 10 20100301
item2 2001 2004 XX 20 20050103
item2 2002 2009 XX 20 20060710
item2 2007 2013 XX 20 20090912
item3 2005 2010 YY 30 20110304
I hope I explained it well. For example if user is looking for available items in year 2011, item1 (with eff. date 20100301) and item 2 (with eff. date 20090912) will be returned.
If someone is looking for items available in year 2008: item2 (with eff. date 20090912) and item 3 will be returned. Item 1 will not be returned in this case because the most recent record for item 1 has range of 2009-2013.
I think I have the first part of the query right, but I dont know how to select the valid records from that results based on the year in one query.
select name,id1,id2,max(effdate)
from [table]
group by name,id1,id2
Any help would be much appreciated.