sql server - How to include loan rules in Employee and Loan sql query? -
i have 3 tables employee
, loan
, loaninstallment
.
employee
table has 1 many relation loan
, , loan
has 1 many loaninstallment
.
employee
(empid, name, isonprobation)loan
(loanid, empid, startdate, enddate).
now need write query fetch records of employee in following output.
output records (empid, name, status, reason)
rules
if employee has not taken loan never status should eligible , reason loan not taken.
if employee has taken loan within 1 year (i.e enddate less 1 year) status should not eligible , reason loan taken.
if employee on probation status should not eligible , reason on probation
if employee has taken laon 1 year ago status should eligible , reason loan taken 1 year ago.
i have written simple query unable understand how include 4 rules , include reason column in single query.
select e.employeeid, e.fullname,l.enddate, (case when datediff(year, max(l.enddate), getdate()) < 0 'eligible' else 'not eligible' end) status employee e left join loan l on e.employeeid = l.employeeid group e.employeeid, e.fullname, l.enddate
you can add rest of conditions case statement. reason column, case statement pretty same instead of status need set reason. also, case when datediff(year, max(l.enddate), getdate()) < 0
wrong result can never less 0.
this should it:
select e.employeeid, e.fullname,l.enddate, (case when l.employeeid null 'eligible' when datediff(month, max(l.enddate), getdate()) > 12 'eligible' when datediff(month, max(l.enddate), getdate()) =< 12 'not eligible' when l.isonprobation = 1 'not eligible' else 'not eligible' end) status, (case when l.employeeid null 'loan not taken' when datediff(month, max(l.enddate), getdate()) > 12 'loan taken on 1 year ago' when datediff(month, max(l.enddate), getdate()) <= 12 'loan taken' when l.isonprobation = 1 'on probation' else 'not eligible' end) reason employee e left join loan l on e.employeeid = l.employeeid group e.employeeid, e.fullname, l.enddate
Comments
Post a Comment