SQL显示最多2名员工雇用了每个部门2021年的最新员工

发布于 2025-02-09 15:59:44 字数 638 浏览 2 评论 0 原文

SQL Server数据库有2个表:

  • Department :ID
  • 员工:ID,部门,Employee_name,date_hired

我想显示最多2名员工雇用了最新的2021年,每个部门

例如

输出应为

我有这个SQL:

SELECT e.* 
FROM Employee e
WHERE e.Date_Hired IN (SELECT e.Date_Hired
                      FROM Employee e
                      WHERE YEAR(e.Date_Hired) = 2021)
ORDER BY e.Date_Hired DESC

但是它正在显示部门1中的所有3个项目

A SQL Server database has 2 tables:

  • Department: Id
  • Employee: Id, Department, Employee_Name, Date_Hired

I wanted to display maximum 2 employees hired the latest in 2021 per department

For example

The output should be

I have this SQL:

SELECT e.* 
FROM Employee e
WHERE e.Date_Hired IN (SELECT e.Date_Hired
                      FROM Employee e
                      WHERE YEAR(e.Date_Hired) = 2021)
ORDER BY e.Date_Hired DESC

But it is displaying all 3 items from department 1.

Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

断爱 2025-02-16 15:59:46
SELECT e.*
FROM Employee e,
     (SELECT id,
             Date_Hired,
             row_number() OVER(PARTITION BY Department ORDER BY id DESC) AS rn
      FROM Employee e
      WHERE YEAR (e.Date_Hired) = 2021) sub
WHERE rn <= 2
  and e.id = sub.id
ORDER by e.Date_Hired DESC
SELECT e.*
FROM Employee e,
     (SELECT id,
             Date_Hired,
             row_number() OVER(PARTITION BY Department ORDER BY id DESC) AS rn
      FROM Employee e
      WHERE YEAR (e.Date_Hired) = 2021) sub
WHERE rn <= 2
  and e.id = sub.id
ORDER by e.Date_Hired DESC
少钕鈤記 2025-02-16 15:59:46

如果您的关系有整数排名
描述每个员工在部门中的职位,
然后,一个简单的条款可以轻松地要求最高的K员工。
因此,您正在寻找等级查询函数:

//learn.microsoft.com/en-us/sql/t-sql/functions/rank-transact-sql?view=sql-sql-server-ver16 。
也许比您的单位测试和未来维护者更微妙
会考虑考虑。

If your relation had integer rank numbers
describing each employee's position within a department,
then a simple WHERE clause could easily request the top K employees.
So you are looking for the rank query function:
https://learn.microsoft.com/en-us/sql/t-sql/functions/rank-transact-sql?view=sql-server-ver16

The relationship among RANK, DENSE_RANK, and ROW_NUMBER is
perhaps more subtle than your unit tests and future maintainers
would care to consider.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文