gpt4 book ai didi

多对一关系的sql查询

转载 作者:行者123 更新时间:2023-12-04 16:10:15 25 4
gpt4 key购买 nike

我有一个包含 3 列的表格

表:StaffDepartmentAssgnment

StaffId         DepartmentId          AssignedFromDate

S1 Dept1 2013-02-08
S2 Dept1 2013-02-08
S3 Dept2 2013-02-01
S1 Dept2 2013-02-01

我想找出当前在 Dept2 中的所有 StaffId。我该如何为它编写查询?

最佳答案

这是一个独立于数据库引擎的解决方案

select * from 
(
select StaffId, max(AssignedFromDate) as adate
from StaffDepartmentAssgnment
group by staffid
) x
inner join StaffDepartmentAssgnment y
on y.staffid = x.staffid and adate = y.AssignedFromDate
where DepartmentId = 'dept2'

SQLFiddle demo

关于多对一关系的sql查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14812091/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com