2016-01-07 43 views
1

我有三個表Employee,LoanLoanInstallment如何在員工和貸款sql查詢中包含貸款規則?

Employee表有一對多的關係與Loan,並Loan有一個 多用LoanInstallment

  • Employee(EMPID,名稱,IsOnProbation)
  • Loan(的LoanID,EMPID,起始日期,結束日期)。

現在我需要編寫一個查詢來獲取僱員的記錄在下面的輸出。

輸出記錄(EMPID,名稱,狀態,原因)

規則

  • 如果員工沒有采取貸款從來沒有那麼它的狀態應該有資格和理由作爲貸款不採取。

  • 如果員工已在一年內貸款(即結束日期是少於一年),那麼它的狀態應該是不符合資格和理由的貸款已被使用。

  • 如果員工是在試用期,然後狀態應該是不符合資格和理由緩刑

  • 如果員工已經採取拉昂1年前那麼狀態應採取1年前資格及原因貸款。

我已經寫了一個簡單的查詢,但我無法理解如何包含所有四個規則,並在此單個查詢中包含Reason列。

SELECT 
    e.EmployeeID, E.FullName,l.EndDate, 
    (CASE 
     WHEN DATEDIFF(YEAR, max(l.EndDate), GETDATE()) < 0 
      THEN 'Eligible' 
      ELSE 'Not Eligible' 
    END) as Status 
FROM 
    Employee e 
LEFT JOIN 
    Loan l ON e.EmployeeID = l.EmployeeID 
GROUP BY 
    e.EmployeeID, e.FullName, l.EndDate 

回答

1

您可以將其餘的條件添加到case語句中。 至於Reason列,你的case語句將幾乎相同,但不是你需要設置原因的狀態。 此外,case when DATEDIFF(YEAR, max(l.EndDate), GETDATE()) < 0是錯誤的,因爲結果可能永遠不會小於0

這應做到:

select e.EmployeeID, E.FullName,l.EndDate, 
     (case when l.EmployeeID is null then 'Eligible' 
      when DATEDIFF(month, max(l.EndDate), GETDATE()) > 12 then 'Eligible' 
      when DATEDIFF(month, max(l.EndDate), GETDATE()) =< 12 then 'Not Eligible' 
      when l.IsOnProbation = 1 then 'Not Eligible' 
     else 'Not Eligible' 
     end) as Status, 
     (case when l.EmployeeID is null then 'Loan not taken' 
      when DATEDIFF(month, max(l.EndDate), GETDATE()) > 12 then 'Loan taken over 1 year ago' 
      when DATEDIFF(month, max(l.EndDate), GETDATE()) <= 12 then 'Loan already taken' 
      when l.IsOnProbation = 1 then 'On probation' 
     else 'Not Eligible' 
     end) as Reason 
FROM Employee e 
    left join Loan l on e.EmployeeID = l.EmployeeID 
group by e.EmployeeID, e.FullName, l.EndDate 
+0

感謝餅乾!你拯救了我的一天。 – touseefkhan4pk