mysql - Check maximum value from colomns of table ,table colomn is not known/constant -


i asked question in interview ,i know can use case /greatest function of oracle. interviewer wanted answer dont have change query if new column added. e.g

student english history maths  zzzz    85      55     66 yyyy    47      99     55 

result expected :-

zzzzz english :85 yyyyy history :99 

now if table altered same query should work

student english history maths science zzzz    85      55       66    86 yyyy    47      99       55    11 

result expected :-

zzzzz science :86 yyyyy history :99 

you can answer in oracle using unpivot:

select *   (   select t.*,          row_number() on ( partition student order total desc ) rn     your_table   unpivot ( total subject in ( english, maths, history ) ) t )  rn = 1; 

but need add new column name in clause of unpivot.

however, if use dynamic sql build part of query using data dictionary (i.e. user_tab_columns table):

declare   column_names clob;   sql          clob; begin   select listagg(            column_name,            ','          ) within group ( order column_id )     column_names;     user_tab_columns    table_name  = 'your_table'   ,    column_name <> 'student';    sql := 'select * ( select t.*, row_number() on ( partition student order total desc ) rn your_table unpivot ( total subject in ( ' || column_names || ' ) ) t )  rn = 1;'    execute immediate sql; end; / 

Comments

Popular posts from this blog

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -