编写SQL查询:展示员工姓名、已休天数、可休天数及休假占比
Fixing the SQL Query for Employee Leave Tracking
Let's work through this step by step. Your current query has a few key issues—like incorrect date calculations, a misspelled table name, and tangled subquery logic. Let's build a clean, correct query that returns the exact output you need.
First, Let's Address the Issues in Your Original Query
- Date Calculation Error:
STARTDATE-ENDDATEgives a negative number and doesn’t account for inclusive days (e.g., 1/1 to 1/11 is 11 days, not 10). UseENDDATE - STARTDATE + 1to get accurate leave day counts. - Table Name Typo:
JOBROLESELIGIBELEshould beJOBROLESELIGIBLELE. - Subquery Logic: You can’t compute aliases like
TAKENLEAVEin aWHEREclause, and your subqueries don’t properly aggregate data per employee or join the tables together. - Missing Aggregation: You need to sum leave days per employee instead of checking individual leave records one by one.
Correct SQL Query
Here's the query that will return the expected columns:
SELECT e.EMPLOYEEID, e.FIRSTNAME, e.LASTNAME, NVL(l.LEAVESTAKEN, 0) AS LEAVESTAKEN, j.ELIGIBLE_SICK_LEAVES + j.ELIGIBLE_EARNED_LEAVES AS ELIGIBLELEAVES, ROUND((NVL(l.LEAVESTAKEN, 0) / (j.ELIGIBLE_SICK_LEAVES + j.ELIGIBLE_EARNED_LEAVES)) * 100, 2) AS PERCENTAGE FROM Employee24 e LEFT JOIN ( -- Calculate total leave days per employee SELECT EMPLOYEEID, SUM(ENDDATE - STARTDATE + 1) AS LEAVESTAKEN FROM Leave25 GROUP BY EMPLOYEEID ) l ON e.EMPLOYEEID = l.EMPLOYEEID JOIN JOBROLESELIGIBLELE j ON e.JOBROLES = j.JOBROLES ORDER BY e.EMPLOYEEID;
Breakdown of the Query
- Subquery for Aggregated Leave Days: The inner subquery groups
Leave25by employee ID and sums up total leave days usingSUM(ENDDATE - STARTDATE + 1)—this counts both the start and end dates of each leave period. - Table Joins:
LEFT JOINwith the aggregated leave data ensures employees with no leave records still appear in the results (with 0 leave days).JOINwithJOBROLESELIGIBLELElinks each employee to their job role's leave eligibility.
- Metric Calculations:
NVL(l.LEAVESTAKEN, 0)replacesNULL(for employees with no leave) with 0.ELIGIBLELEAVEScombines sick and earned leave eligibility for the employee's role.PERCENTAGEcalculates the ratio of taken leave to eligible leave, rounded to 2 decimal places for readability.
Expected Result (Matching Sample Data)
| EMPLOYEEID | FIRSTNAME | LASTNAME | LEAVESTAKEN | ELIGIBLELEAVES | PERCENTAGE |
|---|---|---|---|---|---|
| 1 | NULL | NULL | 55 | 38 | 144.74 |
| 2 | NULL | NULL | 13 | 17 | 76.47 |
| 3 | NULL | NULL | 9 | 17 | 52.94 |
(Note: FIRSTNAME and LASTNAME are NULL in the sample data because the Employee24 create statement only populates EMPLOYEEID and JOBROLES.)
内容的提问来源于stack exchange,提问作者user2147357
相关产品推荐
相关产品推荐

