如何更新表

时间:2016-09-08 06:51:23

标签: sql sqlite

我有两个表T1和T2

T1

Id name open   receive close
1  jon  5000    0      5000
2  jim  6000    0      6000
3  ben  9000    0      9000

T2

Id name receive
1  jon   500
3  ben   200
2  jim   700
1  jon   500
2  jim   700
3  ben   100

首先我想要如何使用更新查询来订购T2。

Id name receive
1  jon   500
1  jon   500
2  jim   700
2  jim   700
3  ben   100
3  ben   200

之后,我希望像这样更新T1

Id name  open   receive close
1  jon   5000   1000    4000
2  jim   6000   1400    4600
3  ben   9000    300    8700

我正在使用Sqlite

2 个答案:

答案 0 :(得分:2)

第一个问题

select * from T2 order by Id, receive

第二个问题

update T1
set T1.receive = T2.receive,
    T1.close = T1.open - T2.receive
from T1
inner join (select Id, sum(receive) receive from T2 group by Id) T2
    on T1.Id = T2.Id

答案 1 :(得分:1)

我不知道为什么要更新表格,因为您可以像这样使用select order by子句

Select * from #T2
Order By Id ASC

现在,对于第三个屏幕截图,您可以使用此

Update t1
Set  T1.[receive] = T2.[receive]
,T1.[close] = T1.[open]- T2.[receive]
from #T1 t1
inner join(
Select t2.ID,t2.name,Sum(t2.[receive]) AS [receive] from #T2
Group By ID,name) T2
on T1.Id=T2.Id

如果使用了folleoinf示例

Create Table #T1 (Id int,name nvarchar(255), [open] int,[receive] int, [close] int)

Insert into #T1 Values
(1,'jon',5000,0,5000),
(2,'jim',6000,0,6000),
(3,'ben',9000,0,9000)


Create Table #T2(Id int,name nvarchar(255),[receive] int)

 Insert into #T2 Values
(1,'jon',500),
(3,'ben',200),
(2,'jim',700),
(1,'jon',500),
 (2,'jim',700),
  (3,'ben',100)