mysql - 仅选择一条重复记录的 SQL 查询,基于该记录中的最高日期值
问题描述
我在下面有一个表格,显示了员工的详细信息,以及一个“dateValue”,这是一个基于员工上班时间的数字。如您所见,“Dave”今天打卡了两次,但我只想查看 Dave 最近的打卡时间(数字越大,打卡时间越近)
ID 是 'employee' 和 'clock' 数据库中的一列,将两个数据库链接在一起,这对每个员工都是唯一的。
下表的 SQL
SELECT e.name, e.country, e.role, e.age, c.dateValue FROM employee e left join clock c on e.ID = c.ID
| e.name | e.country| e.role |e.age| c.dateValue | c.ID |
| Dave | England | Programmer | 45 | 013 | 1 |
| Gary | Scotland | Engineer | 44 | 033 | 2 |
| Brian | USA | Engineer | 67 | 042 | 4 |
| Dave | England | Programmer | 45 | 019 | 1 |
| Lucy | England | Sales | 35 | 033 | 5 |
期望的结果:
| e.name | e.country| e.role |e.age| c.dateValue | c.ID |
| Gary | Scotland | Engineer | 44 | 033 | 2 |
| Brian | USA | Engineer | 67 | 042 | 4 |
| Dave | England | Programmer | 45 | 019 | 1 |
| Lucy | England | Sales | 35 | 033 | 5 |
在我想要的结果中,不显示 Dave 的第一个打卡,因为我只想显示每个员工的一个,无论他们今天打卡一次还是 100 次,我只想显示他们最近的打卡,其中c.dateValue 最高,并按 e.name 分组
我试过的SQL:
SELECT e.name, e.country, e.role, e.age, c.dateValue FROM employee e left join clock c on e.ID = c.ID group by e.name where MAX(c.dateValue) AS date
SELECT e.name, e.country, e.role, e.age, MAX(c.dateValue) AS date FROM employee e left join clock c on e.ID = c.ID group by e.name
对于上面我的 SQL 的两次尝试,我都收到错误:“'employee.country' 在选择列表中无效,因为它不包含在聚合函数或 GROUP BY 子句中”
解决方案
您需要过滤,而不是聚合。我会推荐row_number()
(仅在 MySQL 8.0 中可用):
select name, country, role, age, datevalue
from (
select e.*, c.datevalue, row_number() over(partition by c.datevalue order by e.id desc) rn
from employee e
inner join clock c on e.id = c.id
) t
where rn = 1
推荐阅读
- angular - 如何在 Linux 机器中自动重新加载 Angular 4 测试用例。
- c# - 如何在 C# 中序列化和反序列化 geojson
- jquery - 如何使用节点在我的代码中正确要求 jquery 和 JSDOM?
- node.js - AWS SKD node.js - getMetricData 不是函数
- arrays - Angular PrimeNG DataTable 将嵌套的 JSON 显示为一列中的自定义字符串
- c# - Cosmo Sql Db - 使用延续令牌查询数据永远不会完成
- python - 在 NumPy 中将单列添加到矩阵中
- oracle - ORA-00904:“PSTATUSTYPE”:无效标识符 00904。00000 -“%s:无效标识符”*原因:*操作:第 67 行错误,第 11 列
- maven-3 - zeppelin-python 测试失败
- netfilter - 如何在 Ubuntu 18.04 上使用 libnetfilter_conntrack