The first step in gathering this information is to get the giving history of each donor by year. Note that we are using the Year Description field because this is easier to work with in subsequent steps:
select y.yeardesc, p.nameid, sum(p.pledgeamount) as pledgeamount
from campledges p, camappeals a, camyears y
where p.appealid = a.appealid
and a.yearid = y.yearid
group by y.yeardesc, p.nameid
This would give us output like this:
YEARDESC NAMEID PLEDGEAMOUNT
-------- ------ ------------
2000 111 234
2001 111 248
2002 111 254
2000 112 122
2001 112 132
2002 112 142
In the next step, we pivot the year so that it is used as a column. This allows us to see all the donor giving history on a single row.
with pledgesbyyear as
(select y.yeardesc, p.nameid, sum(p.pledgeamount) as pledgeamount
from campledges p, camappeals a, camyears y
where p.appealid = a.appealid
and a.yearid = y.yearid
group by y.yeardesc, p.nameid)
select nameid,
max(decode(yeardesc, '2000', pledgeamount, null)) yr2000,
max(decode(yeardesc, '2001', pledgeamount, null)) yr2001,
max(decode(yeardesc, '2002', pledgeamount, null)) yr2002
from pledgesbyyear
group by nameid
This query would give us output like this:
NAMEID YR2000 YR2001 YR2002
------ ------ ------ ------
111 234 248 254
112 122 132 142
And finally, we combine the last query with additional information about the donor such as their name and address:
with pledgesbyyear as
(select y.yeardesc, p.nameid, sum(p.pledgeamount) as pledgeamount
from campledges p, camappeals a, camyears y
where p.appealid = a.appealid
and a.yearid = y.yearid
group by y.yeardesc, p.nameid),
donorhistory as
(select nameid,
max(decode(yeardesc, '2000', pledgeamount, null)) yr2000,
max(decode(yeardesc, '2001', pledgeamount, null)) yr2001,
max(decode(yeardesc, '2002', pledgeamount, null)) yr2002
from pledgesbyyear
group by nameid)
select n.NameID, n.DisplayName, n.AddressLine1, n.AddressLine2, n.City, n.State, n.Zip,
h.yr2000, h.yr2001, h.yr2002
from camNamesV n, donorhistory h
where n.NameId = h.NameId
This query adds the Display Name and the Primary Mailing address to the results.