[英]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.