简体   繁体   中英

How to calculate in PL/SQL Oracle?

I have 2 columns, each columns have 2 rows. For example

A     B
100   200
200   300

So that I would like to calculate like this

Total A          Total B

200-100 = 100   300-200=100

Show

Total A     Total B
100         100

Using MAX() and MIN() aggregate functions:

SELECT MAX(A) - MIN(A) AS "Total A",
       MAX(B) - MIN(B) AS "Total B"
FROM TableName

Depends on what you exactly want to manage. If the problem is related to the difference between consecutive rows, using lead() or lag() window analytic functions might be a smart way :

with t( a, b ) as
(
 select 100, 200 from dual union all 
 select 200, 300 from dual 
), t2 as
(
select lead(a) over (order by 1) - a as "Total A",
       lead(b) over (order by 1) - b as "Total B",
       row_number() over (order by 1) as rn
  from t        
)
select *
  from t2
 where rn = 1;

Total A  Total B    RN
100      100        1

You can query it like this,

WITH your_table AS 
   (SELECT 100 a, 200 b
      FROM DUAL
     UNION ALL
    SELECT 200 a, 300 b
      FROM DUAL
     ORDER BY 1 DESC)
SELECT SUM(DECODE(ROWNUM, 1, a, -1*a)) TOTAL_A, SUM(DECODE(ROWNUM, 1, b, -1*b)) TOTAL_B
  FROM your_table;

You can try this as below

Select * , `entity1`-`entity2` As `entity3` 
FROM tbl

Hope this helps.

Bro their is two understanding in your question first you want to delete from max value and which solution provided to you by someone else and other is you want to delete from last row/second row. So the solution is provided to you for second approach. please discuss if any query.

select sum(Result.A) as A, sum(Result.B) as B, from (
    select top 1 A , B from Table_name order by id_row_order desc
    union all
    select top 1 - A , -B from Table_name order by id_row_order Asc
) as Result

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM