I need to somehow use the CASE syntax (which is beyond me) to affect the database results based on criteria. I have a bunch of royalties in 0.# form (royalty) I have a title ID # (title_id) and I need to show the new increase in royalties so that I can use the data.
IF: they have a current royalty of 0.0 - 0.1 = 10% raise
IF: they have 0.11 - 0.15 = 20% raise
IF: royalty >= 0.16 = 20% raise
Any help would be much appreciated.
create table royalites (
title_id char(6),
lorange integer,
hirange integer,
royalty decimal(5,2));
SELECT EMPNO, LASTNAME, CASE SUBSTR(WORKDEPT,1,1) WHEN 'A' THEN 'Administration' WHEN 'B' THEN 'Human Resources' WHEN 'C' THEN 'Design' WHEN 'D' THEN 'Operations' END FROM EMPLOYEE; Example 2 (searched-when-clause): You can also use a CASE expression to avoid division by zero errors.
A CASE expression is, in fact, allowed inside the WHERE clause.
The SQL CASE ExpressionThe CASE expression goes through conditions and returns a value when the first condition is met (like an if-then-else statement). So, once a condition is true, it will stop reading and return the result. If no conditions are true, it returns the value in the ELSE clause.
SQL Case Statement Syntax Then for a single condition you can write the keyword WHEN followed by the condition that has to be satisfied. After that comes the keyword THEN and the value for that condition, like WHEN <condition> THEN <stuff> . This can then be followed by other WHEN / THEN statements.
Actually, you don't need to use the case
statement:
update royalties set royalty = royalty * 1.2
where royalty >= 0.16;
update royalties set royalty = royalty * 1.2
where royalty >= 0.11 and royalty < 0.16;
update royalties set royalty = royalty * 1.1
where royalty < 0.11;
(under transactional control if you need atomicity). You could possibly combine the first two if they have the same multiplier as your question states.
It works by ensuring you do the higher values first and limit what rows get affected in the where
clause.
If you feel you must use a case
statement:
update royalties set royalty =
case when royalty >= 0.16 then royalty * 1.2
case when royalty >= 0.11 and royalty < 0.16 then royalty * 1.2
case when royalty < 0.11 then royalty * 1.1
end;
To just change what you're pulling out of the table (rather than changing the table itself) and compare it with the current:
select title_id, lorange, hirange, royalty,
case when royalty >= 0.16 then royalty * 1.2
case when royalty >= 0.11 and royalty < 0.16 then royalty * 1.2
case when royalty < 0.11 then royalty * 1.1
end as new_royalty
from royalties;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With