Skip to content
Advertisement

Subtracting a value in a column based on condition using PLSQL

A simple thing to do I believe.
Say I have a table:

CREATE TABLE kpi
( KPI_ID number(10) NOT NULL,
  KPI_NAME varchar2(50) NOT NULL,
  DAY_DATE DATE
);

And I know thet someone made a mistake and added 100 to all values higher than 100 when the table was created.
I need a query where 100 is subtracted from all values in KPI_ID column that are >100.
And I only have access to a read mode

Advertisement

Answer

someone made a mistake and added 100 to all values higher than 100 when the table was created … I need values ​​that are less than 100 to remain intact, and those that are greater than or equal to 100 should be reduced by 100

You need to conditionally apply an adjustment to the KPI_ID. For this we use case() statements:

select case when (kpi_id - 100) >= 100 then 
         kpi_id - 100 
       else
         kpi_id 
       end as kpi_id
       , kpi_name
       , day_date
from kpi
;

In your original question you said “all values in KPI_ID column that are >100” but in your latest comment you say “greater than or equal to 100”. My amended solution implements the algorithm from your comment, on the assumption that the most recently stated requirement is always right.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement