Siva Academy

Youtube.com/SivaAcademy  Oracle SQL  |  PLSQL  |  SQL PLSQL Interview Questions  |  PLSQL Scenario based Interview Questions  |  Subscriber Questions & Answers

  |  SQL practical Question  |  SQL Performance Tuning  |  New Features  |  

  Trigger     |    View  

Monday, June 22, 2020

SQL to find max value across row and column


SQL to find max value across row and column

























drop table t;
create table t(c1 number, c2 number, c3 number);

insert into t values(1,2,3);
insert into t values(4,5,6);
insert into t values(7,8,9);

commit;

select
max(greatest(c1,c2,c3)) col_value
from t;

---------------------------------------------------

with d as (
select 'C1' col_name,max(c1) val from t
union
select 'C2',max(c2) from t
union
select 'C3',max(c3) from t)
select *
from d
where val = (select max(val) from d);

---------------------------------------------------

with d as (select 'C1' col_name,c1 val from t
union
select 'C2',c2 from t
union
select 'C3',c3 from t)
select * from (
select col_name,case when val =  max(val) over() then val end val
from d)
where val is not null;

---------------------------------------------------

select column_name,col_val from (
select column_name,col_val, max(col_val) over() m_val
from t
UNPIVOT (col_val for column_name in (c1,c2,c3)))
where col_val = m_val

---------------------------------------------------

3 comments:

  1. If we need to find out which column the max value present the how it would be?

    ReplyDelete
  2. with c as (
    select max(c1) as one,max(c2) as two,max(c3) as third from t)
    select greatest(one,two,third) from c

    i tried this method i find max of each column first then using greatest ( function) i compare all three column values to get the max of all

    ReplyDelete
  3. select max(greatest(c1,c2,c3)) from t

    ReplyDelete