根据SQL Server中返回的查询更新表

时间:2013-05-02 11:10:52

标签: sql sql-server sql-server-2008

我遇到了更新查询。我有一个查询

SELECT s_no, loan_id,repayment_date,principal,loan_balance, count(*) as repeatTimes
FROM loan_repayment_plan_mcg  
GROUP BY s_no, loan_id, repayment_date,principal,loan_balance
HAVING count(*) > 1

它返回此输出:

s_no    loan_id   repayment_date    principal   loan_balance    repeatTimes
1         21111   2012-03-13            0.00    5000.00            2
2         21311   2012-04-12            0.00    2000.00            2
3         21111   2012-05-13            500     5000.00            2
4         21111   2012-06-14            0.00    5000.00            3

我希望根据loan_balancerepeatTimes从我上面的选择查询中loan_id乘以repayment_date,并将{{1}}组合在一起以形成唯一的行。

1 个答案:

答案 0 :(得分:1)

传统方式,使用JOIN中的UPDATE

update A
set loan_balance = loan_balance * repeatTimes
from loan_repayment_plan_mcg A
join
(
SELECT s_no, loan_id,repayment_date,principal,loan_balance, count(*) as repeatTimes
FROM loan_repayment_plan_mcg  
GROUP BY s_no, loan_id, repayment_date,principal,loan_balance
HAVING count(*) > 1
) B on A.s_no = B.s_no
   and A.loan_id = B.loan_id
   and A.repayment_date = B.repayment_date
   and A.principal = B.principal
   and A.loan_balance = B.loan_balance;

在SQL Server 2008中使用窗口函数和CTE

;with cte as (
  SELECT *,sum(loan_balance) over (
             partition by s_no,loan_id,repayment_date,principal,loan_balance) total_balance
  FROM loan_repayment_plan_mcg
)
update cte
   set loan_balance = total_balance
 where loan_balance != total_balance;