在Oracle中选择列的最大值

时间:2010-01-31 22:56:09

标签: sql oracle

我有一个包含这样数据的表

id    test_val    type_cd  
#-------------------------  
101   TEST22      M  
102   TEST23      M  
103   TEST01      M  
103   TEST01      H  
104   TEST02      M  
104   TEST02      H  
105   TEST03      H  

我想在单行输出中获取每个type_cd及其对应的test_val的max(id),如下所示。

预期输出为:

M_id  M_Test_Val   H_id   H_Test_Val  
#-----------------------------------
104   TEST02       105    TEST03  

如果我只需要为每个type_cd获取最大值(id),我会像这样查询

select max(case when type_cd='M' then max(id) else null end) as M_id,
       max(case when type_cd='H' then max(id) else null end) as H_id
from t1
group by type_cd;

我不确定如何为每个max(id)获取type_cd的test_val。

2 个答案:

答案 0 :(得分:1)

这是分析函数自成一体的场景......

select type_cd
       , id as max_id
       , test_val
from ( 
        select type_cd
               , id
               , test_val
               , rank () over (partition by type_cd order by id desc) as rank_id
        from your_table
     )
where rank_id = 1
/

修改

上述查询无法满足您对单行的需求。将查询插入这样的CTE应该这样做......

with subq as 
    (    select type_cd
           , id as max_id
           , test_val
    from ( 
            select type_cd
                   , id
                   , test_val
                   , rank () over (partition by type_cd 
                                       order by id desc) as rank_id
            from your_table
         )
    where rank_id = 1 )
select m.id as m_id
       , m.test_val as m_test_val
       , h.id as h_id
       , h.test_val as h_test_val
from ( select * from subq where type_cd = 'M') m
     join ( select * from subq where type_cd = 'H') h 

/

答案 1 :(得分:0)

我编写了如下代码,它按预期工作。

select max(case when type_cd='M' then id else null end) as m_id,  
max(case when type_cd='M' then test_val else null end) as m_test_val,  
max(case when type_cd='H' then id else null end) as h_id,  
max(case when type_cd='M' then test_val else null end) as h_test_val  
from  
    ( select type_cd ,  
             id ,  
             test_val ,  
             rank () over (partition by type_cd order by id desc) as rank_id  
      from your_table )  
where rank_id = 1;  

不确定这是否是最佳方式。但就像我想要的那样工作。