[英]How to get maximum value of value1 from table where value1 and value2 fields ignoring value2 field
我的表具有column1 =日期,column2 = A / B,column3 = id。 我想要的结果是,与ID比较的最新日期应为column2中的B,如果A则忽略
表
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
预期结果
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
使用相关子查询
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
假设c1列为有效日期,您可以尝试对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
或者,如果您还需要与您的ID不匹配的ID,请附加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
如果只希望将c3
值与指标一起使用,则可以使用聚合:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.