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