我有一张表ABC,其中包含以下记录 -
INVC_NUM | LINE_NUMBER | ORGANIZATION_ID | STATUS | DATE
0000034454 1 521 Validated 09/09/2016
0000034454 2 521 Validated 04/09/2016
0000034410 1 521 Validated 04/09/2016
0000034410 2 521 notValidated 04/09/2016
0000034410 3 521 notValidated 04/09/2016
0000034410 4 521 Validated 04/09/2016
现在我需要更新一个包含以下列的表XYZ
INVC_NUM | ORGANIZATION_ID | date
0000034454 | 521 | 09/09/2016
0000034410 | 521 | null
每当特定INVC_NUM和organization_id的所有Line_number的状态都被“全部”验证(状态)时,我们需要使用最大(DATE)FOR INVC_NUM更新XYZ。
每当特定INVC_NUM和organization_id的所有Line_number的状态都未被验证(状态)时,我们需要使用NULL更新XYZ。 XYZ具有每个INVC_NUM和Org_id的唯一记录。
答案 0 :(得分:0)
这应该可以更新完全验证的organized_id/invc_num
组合及其最长日期,否则NULL
:
UPDATE XYZ
SET DATE = CASE WHEN NOT EXISTS (SELECT *
FROM ABC
WHERE ABC.ORGANIZATION_ID = XYZ.ORGANIZATION_ID
AND ABC.INVC_NUM = XYZ.INVC_NUM
AND ABC.Status = 'notValidated')
THEN (SELECT MAX(DATE)
FROM ABC
WHERE ABC.ORGANIZATION_ID = XYZ.ORGANIZATION_ID
AND ABC.INVC_NUM = XYZ.INVC_NUM)
ELSE NULL
END;
答案 1 :(得分:0)
您可以使用MERGE
语句进行更新。大多数工作都在USING
子句中的聚合子查询中完成。我将日期列名称从date
更改为dt
- 不要将Oracle关键字用作列名。
merge into xyz
using (
select invc_num, organization_id,
case when max(case when status = 'Validated'
then dt else date '9999-12-31' end)
= date '9999-12-31'
then null
else max(dt) end as dt
from abc
group by invc_num, organization_id
) g
on (xyz.invc_num = g.invc_num and xyz.organization_id = g.organization_id)
when matched then update
set xyz.dt = g.dt
;