Sum and Difference

       

Write an SQL query to see if the sum or difference of numbers from the first 2 columns results in the number in the third column from the table.



Input :-

Sum table :-
A, B and C are the Primary Key for the Sum table.

A

B

C

12

18

30

5

8

10

15

2

13

8

6

25


Output :-

A

B

C

Result

12

18

30

Yes

5

17

10

No

15

2

13

Yes

8

6

25

No



Query :-
select A, B, C,
CASE
    WHEN A+B=C or
    A-B=C THEN 'Yes'
    ELSE 'No
END Result
From Sum;

Explanation : - 

This query selects three columns A, B, and C from a table named "Sum." It also includes a CASE statement to generate a calculated column called ‘Result’.


The CASE statement checks two conditions using the WHEN keyword. It evaluates whether the sum of A and B is equal to C or if the difference between A and B is equal to C. If either of these conditions is true, the corresponding row will have the value 'Yes' in the Result column. Otherwise, the value 'No' will be assigned to the Result column.


In summary, this query examines each row in the "Sum" table and determines if either the sum or the difference of columns A and B matches the value in column C. It then outputs 'Yes' if the condition is satisfied or 'No' if it is not.











No comments

darkmode