【问题标题】:How to include loan rules in Employee and Loan sql query?如何在 Employee 和 Loan sql 查询中包含贷款规则?
【发布时间】:2016-01-07 15:30:33
【问题描述】:

我有三个表EmployeeLoanLoanInstallment

Employee 表与Loan 具有一对多关系,而Loan 具有一对多关系 许多与LoanInstallment

  • Employee(EmpId、姓名、IsOnProbation)
  • Loan(LoanId、EmpId、StartDate、EndDate)。

现在我需要编写一个查询来获取以下输出中的员工记录。

输出记录(EmpId、名称、状态、原因)

规则

  • 如果员工从未贷款,则其状态应为合格,并且理由为未贷款。

  • 如果员工在一年内贷款(即 EndDate 不到一年),则其状态应为不合格并说明已贷款。

  • 如果员工处于试用期,则状态应为不合格且试用期原因

  • 如果员工在 1 年前使用了 laon,则状态应为 Eligible 并且 Reason Loan 在 1 年前使用。

我编写了一个简单的查询,但我无法理解如何在这个单一查询中包含所有四个规则并包含原因列。

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

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:

    您可以将其余条件添加到您的案例语句中。 至于原因列,您的案例陈述将几乎相同,但不是您需要设置原因的状态。 另外,case when DATEDIFF(YEAR, max(l.EndDate), GETDATE()) &lt; 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
    

    【讨论】:

    • 谢谢曲奇!你拯救了我的一天。
    猜你喜欢
    • 1970-01-01
    • 2020-03-14
    • 1970-01-01
    • 1970-01-01
    • 2022-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-07
    相关资源
    最近更新 更多