2

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
4

2 回答 2

0

只要您只想要这三年范围,一个简单的方法是:

SELECT f.id, f2011.rate, f2010.rate, f2009.rate
FROM (SELECT id FROM fields GROUP BY id) f
LEFT JOIN fields f2011 ON f.id = f2011.id AND f2011.date >= '01.01.2011' AND f2011.date < '31.12.2011'
LEFT JOIN fields f2010 ON f.id = f2010.id AND f2010.date >= '01.01.2010' AND f2010.date < '31.12.2010'
LEFT JOIN fields f2009 ON f.id = f2009.id AND f2009.date >= '01.01.2009' AND f2009.date < '31.12.2009'

否则结帐 PIVOT。

于 2012-04-12T18:55:04.427 回答
0

你可以PIVOT这样使用:

create table #temp
(
    id int,
    date datetime,
    rate decimal(10,2)
)

insert into #temp values(1, '12/12/11', 1.2)
insert into #temp values(1, '08/10/10', 1.8)
insert into #temp values(2, '01/01/09', 0.2)
insert into #temp values(2, '03/12/08', 0.5)
insert into #temp values(3, '06/01/12', 1.1)
insert into #temp values(3, '07/20/10', 0.9)

select *
from 
(
    select id, rate, year(date) as yearDate
    from #temp
) x
pivot
(
    max(rate)
    for yearDate in([2011], [2010], [2009], [2008])
) p

drop table #temp
于 2012-04-16T14:32:56.040 回答