I have this three table with many-to-many relation between account and bounse , i want to compare the bounse for each account with the previous month by subtract current month's bounse with the previous month
tbl_account
account_id account_name
----------- ---------------------
1 Account1
2 Account2
tbl_bounse
bounse_id bounse_name
----------- -------------
42 bounseA
43 bounseB
44 BounseC
tbl_detail ( the link table between tbl_account and tbl_bounse )
detail_accound_id detail_bounce_id detail_value detail_id detail_date
----------------- ---------------- -------------------- ----------- -----------
1 42 24000 158981 2013-05-05
1 42 25000 159113 2013-06-06
1 43 150 158982 2013-05-05
1 43 150 159114 2013-06-06
1 44 23000 158983 2013-05-05
1 44 25150 159115 2013-06-06
2 42 20000 159025 2013-05-05
2 42 23000 159157 2013-06-06
2 43 400 159026 2013-05-05
2 43 350 159158 2013-06-06
2 44 10000 159021 2013-05-05
2 44 11000 159159 2013-06-06
and I want to summarize the result as
accound_id detail_date BounseA BounseB BounseC
----------- ----------- ------- ------- -------
1 2013-05-05 24000 150 23000
1 2013-06-06 25000 150 25500
1 differ date 1000 0 2500
2 2013-05-05 20000 400 10000
2 2013-06-06 23000 350 11000
2 differ date 3000 -50 1000
returned Temp Table as
accound_id detail_date BounseA BounseB BounseC
----------- ----------- ------- ------- -------
1 differ date 1000 0 2500
2 differ date 3000 -50 1000
i'm trying to use pivot and dynamic sql but i don't know how to subtract the rows and insert the result of subtracting into temp table
SQL server 2008 r2 , the query using T-SQL or LINQ