SQL - 来自临时表的{INSERT AND UPDATE表

时间:2017-06-14 14:37:07

标签: sql sql-server stored-procedures

我正在尝试将一些数据插入临时表(#temptable),插入后我想执行Sum(金额),它与相同的ID和组匹配的是cust的名称和账单ID,我想选择这些匹配ID中可用的最早日期。完成所有这些操作后,我想更新原始表(billtable)

Bill ID   Amount  CUstName   Duedate

12         12.2     ABC        12222016
12         22.2     ABC        12112016
13         23.22    ABC        12102016

Bill ID   Amount  CUstName   Duedate

12         34.4     ABC        12112016
13         23.22    ABC        12102016

1 个答案:

答案 0 :(得分:0)

你需要类似下面的内容

If(OBJECT_ID('tempdb..#t') Is Not Null)
Begin
    Drop Table #t
End

 create table #t
(
billid varchar (50),
amount decimal,
cust varchar (50),
duedate datetime
)

insert into #t (billid,amount,cust,duedate) values ('12',12.2,'abc','20161222')
insert into #t (billid,amount,cust,duedate) values ('12',22.2,'abc','20161211')
insert into #t (billid,amount,cust,duedate) values ('13',23.22,'abc','20161210')
insert into #t (billid,amount,cust,duedate) values ('12',34.4,'abc','20161211')
insert into #t (billid,amount,cust,duedate) values ('13',23.22,'abc','20161210')

select billid,sum(amount),MIN(duedate)
from #t
group by billid