mysql - 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
谢谢你,萨默
解决方案
如果有任何值,请使用聚合:
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;
推荐阅读
- spring - spring-boot-starter-jdbc DAO 存储库对象未注入工作的旧版 Web 服务
- undefined - 错误 C2027 使用未定义类型“UItem”
- html - 使用 Python 和 Airflow 在电子邮件中发送 Redshift 查询结果
- oauth-2.0 - 用于描述 OAuth 2.0 使用的访问控制方法的“正确”术语是什么?
- javascript - 如果属性值不为null,如何获取对象属性及其属性值然后转换对象属性?
- c# - Unity AudioManager PlayerPrefs 滑块
- f# - Saturn Value restriction error when module is in separate file
- c# - 更正无效的 Json 字符串并将其转换为 C# 类
- javascript - 当用户使用javascript按下keybaord箭头键时如何更改图像
- pandas - 使用特定值在 python 中绘制条形图