日期:2014-05-18  浏览次数:20494 次

高手看一下这个SQL怎么写

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

表A
内码     人员编号 奖金
1 2 100
2 1 200
3 4 20
4 4
5 1 10
6 1
7 2
8 1
9 2
10 2
11 0
12 0
13 4


------解决方案--------------------
用關聯的話

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
這幾步思路一起合起來就是最上面的語句了。