[英]Oracle: Updating from self-join
Given this table: 给定此表:
MODEL RESULT DATE SECTION
AABBCC 10.5 1/1/2001 1
AABBCC 15.6 1/1/2001 2
AABBCC 42.2 1/1/2001 3
AABBCC 35.4 1/1/2001 4
AABBCC 82.1 1/1/2001 5
AABBCC 95.3 1/1/2001 6
AABBCC 76.5 1/1/2001 7
I want to make sure that for each section (for the same date/model), the result is always greater than or equal to any preceding section. 我要确保对于每个部分(对于相同的日期/模型),结果始终大于或等于任何前面的部分。
eg If row 7's result is less than row 6's result, I need to set row 7 equal to row 6's result. 例如,如果第7行的结果小于第6行的结果,则我需要将第7行设置为等于第6行的结果。
Similarly, if row 5's result is less than row 2's result, I would need to set row 5's result to row 2's result. 同样,如果第5行的结果小于第2行的结果,则需要将第5行的结果设置为第2行的结果。
I am able to find the cases where a higher section has a lower value than a preceding section using a self-join like this: 我可以使用如下自连接找到较高部分的值比前一个部分低的情况:
SELECT
t1.MODEL as MODEL,
t1.DATE as DATE
t1.RESULT as RESULT_1,
t1.SECTION as SECTION_1,
t2.RESULT as RESULT_2,
t2.SECTION as SECTION_2
FROM table t1
INNER JOIN table t2
ON t1.DATE = t2.DATE AND t1.MODEL = t2.MODEL
WHERE t2.section > t1.section AND
t2.result < t1.result
Which produces the following: 产生以下内容:
MODEL DATE SECTION_1 RESULT_1 SECTION_2 RESULT_2
AABBCC 1/1/2001 3 42.2 4 35.4
AABBCC 1/1/2001 6 95.3 7 76.5
I have attempted to MERGE the data like this: 我试图像这样合并数据:
MERGE INTO table new
USING (
SELECT
t1.MODEL as MODEL,
t1.DATE as DATE
t1.RESULT as RESULT_1,
t1.SECTION as SECTION_1,
t2.RESULT as RESULT_2,
t2.SECTION as SECTION_2
FROM table t1
INNER JOIN table t2
ON t1.DATE = t2.DATE AND t1.MODEL = t2.MODEL
WHERE t2.section > t1.section AND
t2.result < t1.result
) old
ON (new.DATE = old.DATE AND new.section > old.section)
WHEN MATCHED THEN
UPDATE
SET new.result = old.result;
but I get the following error: 但我收到以下错误:
Error report - SQL Error: ORA-30926: unable to get a stable set of rows in the source tables 30926. 00000 - "unable to get a stable set of rows in the source tables" *Cause: A stable set of rows could not be got because of large dml activity or a non-deterministic where clause. 错误报告-SQL错误:ORA-30926:无法在源表30926中获得稳定的行集。00000-“无法在源表中获得稳定的行集” *原因:无法获得稳定的行集由于dml活动较大或不确定的where子句而被获取。 *Action: Remove any non-deterministic where clauses and reissue the dml. *操作:删除所有不确定的where子句,然后重新发出dml。
MERGE INTO table new
USING (
SELECT MODEL,
DATE,
RESULT,
SECTION
FROM (
SELECT
t1.MODEL as MODEL,
t1.DATE as DATE,
MAX(t1.RESULT) OVER (PARTITION BY t1.MODEL ORDER BY t1.SECTION) as RESULT,
t1.SECTION as SECTION,
t1.RESULT as OLD_RESULT
FROM table t1)
WHERE OLD_RESULT != RESULT
) old
ON (new.DATE = old.DATE AND new.section = old.section and new.MODEL = old.MODEL )
WHEN MATCHED THEN
UPDATE
SET new.result = old.result;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.