oracle 比较表的两个值,然后根据条件更新其中一个值

rkue9o1l  于 2023-06-29  发布在  Oracle
关注(0)|答案(3)|浏览(131)

需要比较两个不同表的一个命名列的值。
表A:

Name Marks
Amit   23
Rahul  12
Gaur   10

表B:

Name Marks
Amit   34
Rahul  10
Gaur   10

Condition:-
marks of A != marks of B
then update in table A 
Marks= A-B

最终结果将是:

Name Marks
Amit   -11
Rahul   2
Gaur    10
jexiocij

jexiocij1#

可以使用MERGE语句:

MERGE INTO a
USING b
ON (a.name = b.name)
WHEN MATCHED THEN
  UPDATE
  SET marks = a.marks - b.marks
  WHERE a.marks <> b.marks

其中,对于样本数据:

CREATE TABLE A (Name, Marks) AS
SELECT 'Amit',  23 FROM DUAL UNION ALL
SELECT 'Rahul', 12 FROM DUAL UNION ALL
SELECT 'Gaur',  10 FROM DUAL;

CREATE TABLE b (Name, Marks) AS
SELECT 'Amit',  34 FROM DUAL UNION ALL
SELECT 'Rahul', 10 FROM DUAL UNION ALL
SELECT 'Gaur',  10 FROM DUAL;

然后在MERGE之后,表A包含:
| 标记| MARKS |
| - -----| ------------ |
| -11| -11 |
| 2| 2 |
| 十个| 10 |
fiddle

qybjjes1

qybjjes12#

只需在名称上连接表,然后减去值-

SELECT A.name, CASE WHEN A.Marks <> B.Marks THEN A.Marks - B.Marks ELSE A.Marks END Final_marks
  FROM A
  JOIN B ON A.name = B.name;
c7rzv4ha

c7rzv4ha3#

UPDATE TableA
SET Marks = A.Marks - B.Marks
FROM TableA A
JOIN TableB B ON A.Name = B.Name
WHERE A.Marks <> B.Marks;

相关问题