我有3个表:Employee,Project,ProjectEmployee
Employee
有ID和姓名Project
有ID,Name,StartDate,EndDate ProjectEmployee
有ID,EmployeeID,ProjectID 例如:
EMPLOYEE
ID | Name
----+-------
1 | Amy
2 | Ben
3 | Charlie
PROJECT
ID | Name | StartDate | EndDate
----+-----------+---------------+--------------
1 | P01 | 1-Jan-17 | 1-Feb-17
2 | P02 | 2-Feb-17 | 20-Feb-17
3 | P03 | 15-Mar-17 | 31-Mar-17
4 | P04 | 30-Nov-17 | 30-Dec-17
PROJECTEMPLOYEE
ID | EmployeeID | ProjectID
----+---------------+-------------
1 | 1 | 1
2 | 1 | 2
3 | 1 | 3
4 | 1 | 4
5 | 2 | 1
6 | 2 | 2
7 | 3 | 1
我想创建一个查询,以找出在项目中工作的总返回员工。例如,有3名员工在P01工作,但在P1的EndDate后180天内只有2名员工在后续项目中工作(将一个项目的EndDate与下一个项目进行比较' StartDates)
例如:
结果应列出所有项目及其员工总数和返回员工总数:
Project | TotalEmployees | TotalReturningEmployees
--------+-------------------+-------------------------------------------
P01 | 3 | 2 (Both Amy and Ben returning)
P02 | 2 | 1 (Only Amy worked in P03)
P03 | 1 | 0 (Amy worked in P04, but it's not within 6 months after P03 ended)
P04 | 1 | 0
由于我是SQL的新手,我尝试使用MS Access解决此问题。这是我到目前为止所做的,这可行,但只显示一个项目。
SELECT SelectedProject AS Project,
COUNT(*) AS ReturningEmployees
FROM
(
SELECT DISTINCT
ProjectEmployee.EmployeeID
FROM Project
INNER JOIN ProjectEmployee
ON Project.ID = ProjectEmployee.ProjectID
WHERE (
(ProjectEmployee.EmployeeID IN (
SELECT ProjectEmployee.Employeeid
FROM ProjectEmployee
WHERE ProjectEmployee.Projectid = SelectedProject
)
)
AND ((Project.StartDate)
BETWEEN
(
SELECT Project.EndDate FROM Project WHERE Project.id = SelectedProject
) AND (
(
SELECT Project.EndDate FROM Project WHERE Project.id = SelectedProject
) + 180
)
)
)
) AS Returning;
答案 0 :(得分:0)
此查询可以完成工作
SELECT p3.ID,
(
SELECT COUNT(*) FROM ProjectEmployee p1 WHERE p1.pid = p3.pid
),
COUNT(p2.pid)
FROM Project p3
LEFT JOIN ProjectEmployee p2 ON p2.ProjectID = p3.ID and p2.EmployeeID IN
(
SELECT pe.EmployeeID
FROM ProjectEmployee pe
WHERE pe.StartYear <= DateAdd(month, 6, p3.EndDate)
)
GROUP BY p3.ID