2017-08-25 46 views
1

我有3個表:員工,項目,ProjectEmployeeSQL僱員返回

  • Employee已標識和名稱
  • Project有ID,名稱,起始日期,結束日期
  • ProjectEmployee有ID,僱員,專案編號

例如:

EMPLOYEE

ID | Name 
    ----+------- 
    1 | Amy 
    2 | Ben 
    3 | Charlie 

項目

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的結束日期後180天內在後續項目中只有2名員工的工作(比較一個項目的結束日期到下一個項目的StartDates)

例如:

  • 項目P01,6個月內的後續項目是P02和P03
  • 項目P02,6個月內的後續項目是P03
  • 項目P03,6個月內的後續項目是沒有

結果應該是列出了所有項目,他們的僱員和返回員工總數的總數計數:

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; 
+2

做一個GROUP BY。用例表達式進行條件聚合。 – jarlh

+0

StackOverflow不是「爲我做作業」或「爲我做我的工作」服務。顯示你的嘗試,也許有人可以提供一些建議。 –

回答

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