首页 > 解决方案 > MySQL从B列存在的表中选择不同的A列,或者如果B列没有,则根据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

谢谢你,萨默

标签: mysqlsqlselect

解决方案


如果有任何值,请使用聚合:

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;

推荐阅读