在采访中有人问我这个问题,我已经知道我们可以使用CASE / oracle的greatst函数了。
但是访调员想要一个答案,如果添加了新列,我们就不必更改查询。
例如

Student English history maths
zzzz    85      55     66
yyyy    47      99     55


预期结果:-

zzzzz English :85
yyyyy history :99


现在,如果表被更改,则相同的查询应该工作

Student English history maths science
zzzz    85      55       66    86
yyyy    47      99       55    11


预期结果:-

zzzzz science :86
yyyyy history :99

最佳答案

您可以使用unpivot在Oracle中获得答案:

SELECT *
FROM   (
  SELECT t.*,
         ROW_NUMBER() OVER ( PARTITION BY student ORDER BY total DESC ) AS rn
  FROM   your_table
  UNPIVOT ( total FOR subject IN ( english, maths, history ) ) t
)
WHERE  rn = 1;


但是您需要将新的列名添加到INUNPIVOT子句中。

但是,如果要使用动态SQL,则可以使用数据字典(即USER_TAB_COLUMNS表)来构建查询的该部分:

DECLARE
  column_names CLOB;
  sql          CLOB;
BEGIN
  SELECT LISTAGG(
           column_name,
           ','
         ) WITHIN GROUP ( ORDER BY column_id )
  INTO   column_names;
  FROM   user_tab_columns
  WHERE  table_name  = 'YOUR_TABLE'
  AND    column_name <> 'STUDENT';

  sql := 'SELECT * FROM ( SELECT t.*, ROW_NUMBER() OVER ( PARTITION BY student ORDER BY total DESC ) AS rn FROM your_table UNPIVOT ( total FOR subject IN ( ' || column_names || ' ) ) t ) WHERE  rn = 1;'

  EXECUTE IMMEDIATE sql;
END;
/

关于mysql - 检查表列的最大值,表列未知/常量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45794932/

10-09 00:53