I have 3 fields: ID, Date, Rate. For each ID there are multiple Dates and Rates coming from a table I'll call 'history'
ID Date Rate
1 12/12/11 1.2
1 08/10/10 1.8
2 01/01/09 0.2
2 03/12/08 0.5
3 06/01/12 1.1
3 07/20/10 0.9
....
I need a solution that has ID, Date 2011, Date 2010, Date 2009 with the corresponding rates (or null/blank if no rate entry exists for that year) populating the date fields.
ID Date2011 Date2010 Date2009
1 1.2 1.8 null
2 null null 0.2
3 null 0.9 null
I've struggled at getting a pivot to work with this and am now trying to use case statements.
This is what I have so far:
SELECT id, date, rate,
CASE WHEN date <= '12/31/11' AND date >= '1/1/11' THEN rate END AS '2011',
CASE WHEN date <= '12/31/10' AND date >= '1/1/10' THEN rate END AS '2010',
CASE WHEN date <= '12/31/09' AND date >= '1/1/09' THEN rate END AS '2009'
FROM history
ORDER BY id
problem I am getting now is each different rate has its' own line. ex:
ID Date2011 Date2010 Date2009 1 1.2 null null 1 null 1.8 null 2 null null 0.2 3 null 0.9 null