简体   繁体   中英

How to get maximum value of value1 from table where value1 and value2 fields ignoring value2 field

I have table with column1 = date, column2 = A/B, column3 = id. I want result where latest date comparing to Id should be with B in column2, Ignore if A

Table

C1        C2    C3
10/6/19   A      1
12/6/19   B      1
13/6/19   A      2
09/6/19   A      3
03/6/19   B      1
04/6/19   B      2
12/6/19   B      4
03/6/19   A      5
06/6/19   B      3

Expected result

C3 1 - Valid . Because last value of latest date is B
C3 4 - Valid . Because last value of latest date is B
C3 3 - Invalid. Because last value of latest date is A

Use a correlated subquery

DEMO

select * from t1 a
where c1 =(select max(c1) from t1 b where a.c3=b.c3 )
and c2='B'

OUTPUT:

c1         c2   c3
2012-06-19  B   1
2012-06-19  B   4

Assumin c1 column is valid date You could try using a subquery for max(c1)

select  * 
from my_table m 
inner join  (
  select  id,  max(c1) max_c1 
  from my_table  
  group by id  
) t on t.max_c1 = m.c1 and m.c2='A' and t.id = m.id

Or if you need also the id not matching you coul append uisng UNION

select  * 
from my_table m 
inner join  (
  select  id,  max(c1) max_c1 
  from my_table  
  group by id  
) t on t.max_c1 = m.c1 and m.c2='A'
select  * 
from my_table m 
inner join  (
  select  id,  max(c1) max_c1 
  from my_table  
  group by id  
) t on t.max_c1 = m.c1 and m.c2='A' and t.id = m.id 

union 

select  max(c1), c2, id
  from my_table where id not in (
  select id 
  from my_table m 
  inner join  (
    select  id,  max(c1) max_c1 
    from my_table  
    group by id  
  ) t on t.max_c1 = m.c1 and m.c2='A'
select  * 
  from my_table m 
  inner join  (
    select  id,  max(c1) max_c1 
    from my_table  
    group by id  
  ) t on t.max_c1 = m.c1 and m.c2='A' and t.id = m.id 
)
group by c2, id

If you just want the c3 values with an indicator, you can use aggregation:

select c3,
       (case when group_concat(c2 order by c1 desc) like 'B,%'
             then 'Valid'
             else 'Invalid'
        end) as flag
from t
group by c3;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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