首页 > 解决方案 > 仅选择一条重复记录的 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 子句中”

标签: mysqlsqlgroup-bygreatest-n-per-groupwindow-functions

解决方案


您需要过滤,而不是聚合。我会推荐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

推荐阅读