我有以下两个表: 津贴和范围。 ALLOWANCE具有键列AllowanceID并且对应于每个AllowanceID,将有许多RANGE条目。 Range有一个名为RangeID的主键和一个AllowanceID引用。除此之外,它还有以下几列。
RANGESTART
RANGEEND
POUNDS
SUM
现在,我想写一个查询来匹配两个AllowanceID的范围。即,给定SorceAllowanceID和TargetAllowanceID,我想匹配范围的数量以及源的目标范围值。所以我有以下查询(我这里只使用一列),后跟一个INSERT语句(此处未显示),
UPDATE
(
SELECT
src.pounds AS src_pounds ,
tgt.pounds AS tgt_pounds
FROM
(
SELECT rank() OVER (PARTITION BY PR.ALLOWANCEID ORDER BY PR.RANGESTART) RN
,PR.*
FROM RANGES PR
WHERE PR.ALLOWANCEID=sourceallowanceid
ORDER BY PR.RANGESTART) src ,
(SELECT rank() OVER (PARTITION BY PR.ALLOWANCEID ORDER BY PR.RANGESTART) PN
,PR.*
FROM ranges PR
WHERE PR.aLLOWANCEID=targetallowanceid
ORDER BY PR.RANGESTART) TGT
WHERE src.Rn=tgt.PN
)
SET tgt_pounds = src_pounds;
但这引起了ORA-01779。然后我尝试使用MERGE语句
MERGE INTO
(
SELECT rank() OVER (PARTITION BY PR.ALLOWANCEID ORDER BY PR.RANGESTART) PN
,PR.*
FROM RANGES PR
WHERE PR.ALLOWANCEID=targetallowanceid
ORDER BY PR.RANGESTART) tgt
USING (SELECT rank() OVER (PARTITION BY PR.ALLOWANCEID ORDER BY PR.RANGESTART) RN
,PR.*
FROM RANGES PR
WHERE PR.ALLOWANCEID=sourceallowanceid
ORDER BY PR.RANGESTART) src
ON ( src.RN = tgt.PN )
WHEN MATCHED
THEN
UPDATE
SET tgt.pounds = src.pounds
WHEN NOT MATCHED THEN
--Insert
抛出了ORA-00903。
请指导我如何为此编写查询。
感谢大家,
与Pradeep
答案 0 :(得分:0)
我不相信你可以合并到一个子查询中,这就是为什么你得到ORA-00903:无效的表名。但是,您可以将该子查询更改为视图,它应该可以工作。试试这个,例如:
CREATE VIEW sub-query subqview as
SELECT rank() OVER (PARTITION BY PR.ALLOWANCEID ORDER BY PR.RANGESTART) PN
,PR.*
FROM RANGES PR
WHERE PR.ALLOWANCEID=targetallowanceid
ORDER BY PR.RANGESTART;
MERGE INTO subqview tgt
USING (SELECT rank() OVER (PARTITION BY PR.ALLOWANCEID ORDER BY PR.RANGESTART) RN
,PR.*
FROM RANGES PR
WHERE PR.ALLOWANCEID=sourceallowanceid
ORDER BY PR.RANGESTART) src
ON ( src.RN = tgt.PN )
WHEN MATCHED
THEN
UPDATE
SET tgt.pounds = src.pounds
WHEN NOT MATCHED THEN
--Insert