有人可以通过以下方案帮助我吗?我正在使用SQL Server 2008r2。我需要sql server查询来获得预期的结果。这是我试图做的:
DECLARE @ProjectInvoice TABLE(InvoiceID INT, ProjectID INT, InvoiceAmount float)
DECLARE @ProjectBudget TABLE(ProjectBudgetID INT, ProjectID INT, BudgetAmount float)
INSERT INTO @ProjectBudget VALUES(11,1,100000),(12,1,50000)
INSERT INTO @ProjectInvoice VALUES (12345,1,25000)
,(12346,1, 30000)
,(12347,1, 40000)
,(12348,1, 30000)
,(12349,1, 10000)
select * from @ProjectBudget
select * from @ProjectInvoice
预期结果:
-- 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 --> now only 5k is left budget, whereas we have 30k to deduct, deduct 5k from projectBudget11
-- 12348 1 25k 12 25k --> and the rest 25k from project Budget 12
-- 12349 1 10k 12 15k
答案 0 :(得分:-1)
SELECT p.InvoiceID, p.ProjectID, p.InvoiceAmount, sm.ProjectBudgetID,
sm.BudgetAmount - sm.amt AS runningTot
FROM @ProjectInvoice AS p
INNER JOIN (SELECT i.InvoiceID, b.projectBudgetID, b.BudgetAmount,
SUM(i.InvoiceAmount) OVER (PARTITION BY b.ProjectBudgetID ORDER BY
i.InvoiceId) AS amt
FROM @ProjectBudget AS b
INNER JOIN @ProjectInvoice AS i ON b.ProjectID = i.ProjectID) as sm ON p.InvoiceID = sm.InvoiceId