[英]MySQL select all distinct values from column a for each distinct column b, where count distinct a >1
[英]MySQL Select distinct column A from table where column B exists or if none with column B then latest based on column C
我在表中有以下數據:
Column A, Column B, Column C
ABC , XYZ , 1/1/2019
DEF , null , 1/1/2019
DEF , UVW , 1/2/2019
DEF , null , 1/3/2019
GHI , null , 1/1/2019
GHI , null , 1/3/2019
我想要 A 列,其中 B 列有值或只是最后一次出現。 上表的結果應該是:
ABC, XYZ, 1/1/2019
DEF, UVW, 1/2/2019
GHI. null, 1/3/2019
謝謝你,薩默
如果有任何值,請使用聚合:
select a, max(b), max(c)
from t
group by a;
如果您希望最后一個非NULL
值和c
是唯一的,則:
select t.*
from t
where t.c = (select t2.c
from t t2
where t2.a = t.a
order by (t2.b is not null) desc, t.c desc
limit 1
);
如果c
有重復並且您使用的是 MySQL 8+,那么您也可以這樣做:
select t.*
from (select t.*
row_number() over (partition by a
order by (b is not null) desc, c desc
) as seqnum
from t
) t
where seqnum = 1;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.