sql server - T SQL to join record dynamically -
can me out following scenario. using sql server 2008r2. need sql server query expected result. here tried do:
declare @projectinvoice table(invoiceid int, projectid int, invoiceamount float) declare @projectbudget table(projectbudgetid int, projectid int, budgetamount float) insert @projectbudget values(11,1,100000),(12,1,50000) insert @projectinvoice values (12345,1,25000) ,(12346,1, 30000) ,(12347,1, 40000) ,(12348,1, 30000) ,(12349,1, 10000) select * @projectbudget select * @projectinvoice expected result:
-- expected result --invoiceid projectid invoiceamount projectbudgetid bugetamountleft -- 12345 1 25k 11 75k -- > 100k(original budget) - 25k -- 12346 1 30k 11 45k --> 75k( budget amount left after first invoice) - 30k -- 12347 1 40k 11 5k --> 45k - 40k -- 12348 1 5k 11 0k --> 5k left budget, whereas have 30k deduct, deduct 5k projectbudget11 -- 12348 1 25k 12 25k --> , rest 25k project budget 12 -- 12349 1 10k 12 15k
select p.invoiceid, p.projectid, p.invoiceamount, sm.projectbudgetid, sm.budgetamount - sm.amt runningtot @projectinvoice p inner join (select i.invoiceid, b.projectbudgetid, b.budgetamount, sum(i.invoiceamount) on (partition b.projectbudgetid order i.invoiceid) amt @projectbudget b inner join @projectinvoice on b.projectid = i.projectid) sm on p.invoiceid = sm.invoiceid
Comments
Post a Comment