简体   繁体   English

Oracle SQL:从表中选择两个子集中的最大值

[英]Oracle SQL: Select a Max of of two subsets from table

I have a table that is formatted like: 我有一个表,其格式如下:

Customer Code Date
Cust1    aa   '18-Mar-01'
Cust1    ab   '18-Apr-05'
Cust1    ac   '18-Feb-20'
Cust1    ba   '18-Mar-03'
Cust1    bb   '18-Apr-06'
Cust1    bc   '18-May-30'
Cust2    aa   '18-Jun-08'
Cust2    ab   '18-May-15'
Cust2    ac   '18-May-07'
Cust2    ba   '18-Apr-26'
Cust2    bb   '18-Jun-17'
Cust2    bc   '18-Mar-29'

I am trying to get this: 我试图得到这个:

Customer Code1 Date        Code2 Date
Cust1    ab    '18-Apr-05' bc   '18-May-30'
Cust2    aa    '18-Jun-08' bb   '18-Jun-17'

I am trying to get max of code 'a*' and the date, and 'b*' and the date. 我正在尝试获取代码“ a *”和日期以及“ b *”和日期的最大值。 I have been using max but I only get the date and not the corresponding code. 我一直在使用max,但是我只得到日期而不是相应的代码。 When I use rank I haven't been able to get the second code. 当我使用等级时,我无法获得第二个代码。 Any ideas? 有任何想法吗?

Select c1.cust_num, 
       c1.cust_stat, 
       p1.cs_code, 
       p1.cs_est_comp_date, 
       p1.cs_act_comp_date 
       (select max(t.Cust_Codes.cs_act_comp_date) 
        from t.Cust_Codes 
        where t.cust_code.cs_code in ('AA','A1','A2')) as c1date, 
       (select max(t.Cust_Codes.cs_act_comp_date) 
        from t.Cust_Codes 
        where t.cust_code.cs_code in ('BA','A0','B2')) as c2date, 
from t.Cust c1, 
     t.Cust_Codes p1 
Where c1.cust_num = p1.cust_num (+) 
  and c1.cust_stat = 'O' 

You can use ANSI-standard window functions and conditional aggregation: 您可以使用ANSI标准的窗口函数和条件聚合:

select customer,
       max(case when seqnum = 1 and code like 'a%' then code end) as code_a,
       max(case when seqnum = 1 and code like 'a%' then date end) as date_a,
       max(case when seqnum = 1 and code like 'b%' then code end) as code_b,
       max(case when seqnum = 1 and code like 'b%' then date end) as date_b
from (select t.*,
             row_number() over (partition by substr(code, 1, 1) order by date desc) as seqnum
      from t
     ) t
group by customer;

Oracle has a function called first_value . Oracle有一个名为first_value的函数。

with
  q as(
    select Customer, substr(Code, 1, 1) Ch,
      first_value(Code) over(
        partition by Customer, substr(Code, 1, 1) order by "Date" desc) Code,
      first_value("Date") over(
        partition by Customer, substr(Code, 1, 1) order by "Date" desc) "Date"
    from t
  )
select Customer,
  max(decode(ch, 'a', Code)) Code1, to_char(max(decode(ch, 'a', "Date")), 'rr-Mon-dd') Date1,
  max(decode(ch, 'b', Code)) Code2, to_char(max(decode(ch, 'b', "Date")), 'rr-Mon-dd') Date2
from q
group by Customer;

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

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