我必须在oracle中连续显示列值最高的列名

时间:2014-06-16 05:44:47

标签: sql oracle

COUNTRY     NUM_GUNS MAX_BOR  MAX_DISP
Gt.Britain  40000    45000    32000
Germany     40000    45000    42000
USA         60000    48000    46000
Japan       45000    54000    65000

这是我的表,我需要行中具有最高值的列名。对于Gt.Britain的示例,最大值为45000我想将其显示为max_bor。

谢谢。

3 个答案:

答案 0 :(得分:2)

只需尝试显式,就像那样:

select case 
         when NUM_GUNS = Greatest(NUM_GUNS, MAX_BOR, MAX_DISP) then
           'NUM_GUNS'
         when MAX_BOR = Greatest(NUM_GUNS, MAX_BOR, MAX_DISP) then
           'MAX_BOR'  
         else
           'MAX_DISP'  
       end as MaxColumnName,
       Greatest(NUM_GUNS, MAX_BOR, MAX_DISP) as MaxColumnValue   
  from MyTable 

答案 1 :(得分:0)

您可以使用CASE声明

SELECT COUNTRY,
       CASE WHEN NUM_GUNS > MAX_BOR AND NUM_GUNS > MAX_DISP THEN 'NUM_GUNS' ELSE NUM_GUNS END NUM_GUNS,
       CASE WHEN MAX_BOR > NUM_GUNS AND MAX_BOR > MAX_DISP THEN 'MAX_BOR' ELSE MAX_BOR END MAX_BOR ,
       CASE WHEN MAX_DISP > MAX_BOR AND MAX_DISP > NUM_GUNS THEN 'MAX_DISP' ELSE MAX_DISP END MAX_DISP 
FROM YourTable

输出:


    COUNTRY     NUM_GUNS MAX_BOR  MAX_DISP
    --------------------------------------
    Gt.Britain  40000    MAX_BOR  32000
    Germany     40000    MAX_BOR  42000
    USA         NUM_GUNS 48000    46000
    Japan       45000    54000    MAX_DISP

答案 2 :(得分:0)

以下查询给出包含最大值

的列的结果
`SELECT t.country, 
(CASE
    When t.NUM_GUNS >= t.MAX_BOR 
        then (case when t.NUM_GUNS >= t.MAX_DISP then t.NUM_GUNS else t.MAX_DISP)
    When t.MAX_BOR >= t.MAX_DISP
        then (case when t.MAX_BOR >= t.NUM_GUNS then t.MAX_BOR else t.NUM_GUNS)
    when t.MAX_DISP >= t.NUM_GUNS
        then (case when t.MAX_DISP >= t.MAX_BOR then t.MAX_DISP else t.MAX_BOR))
as max_column

from country_table as t
order by t.country`