sql >> Databasteknik >  >> RDS >> Oracle

Fråga för att hitta anställda som har tagit ut mer än sin kvalificerade ledighet med avseende på sina jobbroller

Detta kommer att hitta varje användare som har överskridit ledighetsbeloppet för varje typ av ledighet:

SQL Fiddle

Oracle 11g R2 Schema Setup :

CREATE TABLE Employee24( EMPLOYEEID, JOBROLES ) AS
SELECT 1, 'RoleA' FROM DUAL UNION ALL
SELECT 2, 'RoleB' FROM DUAL UNION ALL
SELECT 3, 'RoleB' FROM DUAL;

CREATE TABLE Leave25( EMPLOYEEID,LEAVEID, LEAVETYPE, STARTDATE, ENDDATE) AS
SELECT 1,1,'SickLeave',  DATE '2018-01-01', DATE '2018-01-11' FROM DUAL UNION ALL
SELECT 1,2,'SickLeave',  DATE '2018-01-21', DATE '2018-01-31' FROM DUAL UNION ALL
SELECT 1,3,'EarnedLeave',DATE '2018-01-11', DATE '2018-01-21' FROM DUAL UNION ALL
SELECT 1,4,'EarnedLeave',DATE '2018-02-01', DATE '2018-02-11' FROM DUAL UNION ALL
SELECT 1,5,'EarnedLeave',DATE '2018-02-21', DATE '2018-03-03' FROM DUAL UNION ALL
SELECT 2,6,'EarnedLeave',DATE '2018-02-01', DATE '2018-02-13' FROM DUAL UNION ALL
SELECT 3,7,'SickLeave',  DATE '2018-01-01', DATE '2018-01-09' FROM DUAL;


CREATE TABLE JOBROLESELIGIBLELE(JOBROLES, ELIGIBLE_SICK_LEAVES, ELIGIBLE_EARNED_LEAVES) AS
SELECT 'RoleA', 14, 24 FROM DUAL UNION ALL
SELECT 'RoleB',  7, 10 FROM DUAL;

Fråga 1 :

SELECT e.employeeId,
       l.leavetype,
       l.days_leave,
       r.AllowedLeaveAmount
FROM   Employee24 e
       INNER JOIN
       ( SELECT employeeId,
                SUM( enddate - startdate ) AS days_leave,
                leavetype
         FROM   Leave25
         GROUP BY employeeId, leaveType
       ) l
       ON ( e.employeeId = l.employeeId )
       INNER JOIN
       ( SELECT *
         FROM   JobRolesEligibleLE
         UNPIVOT ( AllowedLeaveAmount FOR LeaveType IN (
           Eligible_Sick_Leaves   AS 'SickLeave',
           Eligible_Earned_Leaves AS 'EarnedLeave'
         ) )
       ) r
       ON (    l.leavetype = r.leavetype
           AND e.jobroles   = r.jobroles )
WHERE  l.days_leave > r.AllowedLeaveAmount

Resultat :

| EMPLOYEEID |   LEAVETYPE | DAYS_LEAVE | ALLOWEDLEAVEAMOUNT |
|------------|-------------|------------|--------------------|
|          1 |   SickLeave |         20 |                 14 |
|          1 | EarnedLeave |         30 |                 24 |
|          2 | EarnedLeave |         12 |                 10 |
|          3 |   SickLeave |          8 |                  7 |



  1. Mysql-fråga med Left Join är för mycket långsam

  2. Hur man ändrar fältet för autonumrerings-id till seriell typ i PostgreSQL

  3. Räkna ackumulerad summa i Postgresql

  4. Hur säkerhetskopierar/exporterar man den anslutna Database database.sql-filen i laravel?