简体   繁体   中英

SQL - INSERT AND UPDATE Table from a Temp Table

I am trying to insert some data into a Temp Table(#temptable) and after inserting I would Like to perform Sum(amount) which matches the same ID and group by the cust name and the bill ID and I want to select the earliest date available in those matching ID. After all these Operations I would like to update the original table(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

you will need something like the below

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM