读书人

高手看一下这个SQL如何写

发布时间: 2012-01-23 21:57:28 作者: rapoo

高手看一下这个SQL怎么写

表A记录的是奖金发放记录,其中字段 "内码 "是序时递增的.
现在需要把奖金一栏中的空值更新为对应人员第一次发放的奖金(如将第4行的奖金执行后应更新为20)
如何写这个SQL语句?

表A
内码 人员编号奖金
12100
21200
3420
44
5110
61
72
81
92
102
110
120
134


[解决办法]
用的

Update
A
Set
奖金 = B.奖金
From
A
Inner Join
A B
On A.人员编号 = B.人员编号
Inner Join
(Select Min(内码) As 内码, 人员编号 From A) C
On B.内码 = C.内码 And B.人员编号 = C.人员编号
Where A.奖金 = 0
[解决办法]
Create table EmpBonus
(
ID,
EmployeeNO,
Bonus
)
行句:
update a
set a.bonus = b.bonus
From table as a
left join table as b on a.EmployeeNO = b.EmployeeNO and b.id <a.id
left join table as c on b.EmployeeNO = c.EmployeeNO and c.id <b.id
where a.bonus is null and b.bonus is not null
and c.id is null

思路:
首先查找表中所有金空的 ----where a.bonus is null
然後查找金空的工其第一次金:
分布:
第一步:查找於金空的工相同,但是ID小於其的,且要求查找出的
金非空,保:1:有比其小的,2:的有金
--SQL:left join table as b on a.EmployeeNO = b.EmployeeNO and b.id <a.id
where b.bonus is not null
第二步:已查找出ID比其小,且有金的相次後,我需要保ID是最小的,所以我只
要查找不出其工相同,ID比其小的就明它是最小ID了,
--SQL:left join table as c on b.EmployeeNO = c.EmployeeNO and c.id <b.id
where c.id is null
步思路一起合起就是最上面的句了。


读书人网 >SQL Server

热点推荐