mysql - 在 MySQL 中为每个唯一列选择所有新输入的值
问题描述
drop table if exists aa;
create temporary table aa(`Country` varchar(100),`Month_Year` varchar(100),
`created_at` timestamp NOT NULL DEFAULT current_timestamp());
insert into aa(Country,Month_Year,created_at)
values('Spain1','JUN2020','2020-09-03 14:20:20'),
('Spain2','JUN2020','2020-09-03 14:20:20'),
('Spain3','JUN2020','2020-08-03 14:20:20'),
('Spain4','JUN2020','2020-07-03 14:20:20'),
('Spain5','JUN2020','2020-06-03 14:20:20'),
('Spain6','JUL2020','2020-09-01 14:20:20'),
('Spain7','JUL2020','2020-09-03 14:20:20'),
('Spain8','JUN2020','2020-09-03 14:20:20'),
('Spain9','AUG2020','2020-09-01 14:20:20'),
('Spain10','AUG2020','2020-05-03 14:20:20'),
('Spain11','AUG2020','2020-05-03 14:20:20'),
('Porto1','AUG2019','2020-05-03 14:20:20'),
('Porto2','AUG2019','2020-05-03 14:20:20'),
('Porto2','AUG2019','2020-05-03 13:20:20'),
('Porto2','AUG2011','2020-05-03 13:20:20');
select * from aa;
产生:
如何修改select
查询,以便只保留突出显示的列?逻辑是列中的每个唯一值,只留下每个唯一值Month_Year
最新的行。created_at
Month_Year
解决方案
一个带有子查询的选项过滤器:
select t.*
from aa t
where t.created_at = (
select max(t1.created_at)
from aa t1
where t1.month_year = t.month_year
)
order by created_at desc
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=f7d29f55ff6f3c573aec0887415b87b5
推荐阅读
- sql - 带有日期和时间的 Oracle SQL Case when 语句
- node.js - Angular 8:基于组件在html中动态设置formControlName
- java - JMeter 清除 JDBC 响应数据
- python - 比较两个文件中同名但值不同的两个json文件
- snowflake-cloud-data-platform - 使用可能的 CASE 语句在 Snowflake 中旋转 JSON
- excel - 如何使用 .Cells 满足条件?
- python - 如何在python中将嵌套列表展平为字典?
- javascript - 一个节点在 DOM 中不能有多个父节点;如何规避这个?
- javascript - 如何将元素添加到对象?
- c# - C#:Visual Studio 2019:错误没有被捕获