简体   繁体   English

在Oracle中为列选择最大值

[英]Selecting max value for a column in Oracle

I have a table which has data like this 我有一张桌子,上面有这样的数据

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  

I would like to fetch the max(id) for each type_cd and its corresponding test_val in a single row output as below. 我想在单行输出中为每个type_cd及其对应的test_val获取max(id),如下所示。

The expected output is: 预期的输出是:

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

If I have to fetch only the max(id) for each type_cd I'll have my query like this 如果我只需要获取每个type_cd的max(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;

I'm not sure how to get the test_val for the max(id) for each type_cd . 我不确定如何为每个type_cd获取max(id)的test_val。

This is the sort of scenario where analytic functions come into their own.... 这是分析功能发挥作用的一种情况。

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
/

edit 编辑

The above query doesn't satisfy your need for a single row. 上面的查询无法满足您对单行的需求。 Slotting that query into a CTE like this ought to do it... 像这样将查询插入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 

/ /

I wrote the code as below and it works as expected. 我写了下面的代码,它可以按预期工作。

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;  

Not sure if this is the optimal way. 不知道这是否是最佳方法。 But works just as I want it to. 但是可以按照我想要的方式工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM