I am perplexed by this complicated (at least for me) challenge. I will break this question into several steps to make it easier to understand.Step 1I am working with a database that records donations and I've created a view that generates a running total for each donor's ID (giftid). The results of the SQL are as follows:giftkey giftid gifteffdat giftamt Running_Total00001 01 1/1/2012 $1000 $100000002 01 2/1/2012 $500 $150000003 01 3/1/2012 $200 $170000004 02 1/5/2012 $100 $10000005 02 4/1/2012 $200 $300Etc...
The SQL that is used to generate these totals:SELECT TOP (100) PERCENT giftkey, giftid, gifteffdat, giftamount, (SELECT SUM(giftamount) AS Expr1 FROM dbo.gifts_full AS G2 WHERE (giftkey <= G1.giftkey) AND (giftid = G1.giftid) AND (gifttype IN ('g', 'y', 'b', 'c'))) AS Running_TotalFROM dbo.gifts_full AS G1WHERE (gifttype IN ('g', 'y', 'b', 'c'))ORDER BY giftid, gifteffdat
All seems good. What I want to do now...Step 2A good number of these individuals in the database also have a spouse in the database with his/her own totals (the relationship is recorded in a table as described further below). Instead of the running totals calculating for each individual, I would like the generate a running total for the 'couple' if they are married, so that the results are like the below example, where persons with the IDs of 05 and 55 are a married couple.Key ID Date Amt Running_Total00111 05 1/2/2012 $500 $50000112 55 1/3/2012 $300 $80000159 05 2/5/2012 $1000 $180000207 55 3/6/2012 $2000 $3800
Each person with a spouse also in the database has that relationship recorded in the relationship table as shown below:ID RelType RelID05 Spouse 5555 Spouse 05
Step 3Preferable, I would like to create a household ID for all entries, so that the above couple has a household id of something like 'H05' or 'H55' and a person with no spouse would have a household id of 'I47' where 47 is their ID number in the system and 'I' was appended in the view.The final results would be a a running total with both the individual ID, household id, and the running total either for the individual or the couple, as below:Key ID HldID Date Amt Running_Total00111 05 H05 1/2/2012 $500 $50000112 55 H05 1/3/2012 $300 $80000159 05 H05 2/5/2012 $1000 $180000207 55 H05 3/6/2012 $2000 $380000358 47 I47 3/1/2012 $50 $5000398 47 I47 6/1/2012 $100 $150
For a couple's household ID, I still need to figure out which criteria will determine which of the individual IDs would be used as the household ID with the 'H' appended in the front, but for now it does not matter.Now, is this a difficult task to accomplish with SQL?