MySQL 5.1无窗口函数时实现按员工分组的配送状态标记SQL方案咨询
Solution for Employee Status Calculation
Let's break down the problem and build the SQL query step by step to meet your requirements. Here's a working solution that handles all the status rules correctly, grouped by Emp_ID:
SELECT Emp_ID, DELIVERY_TIME, CASE -- Rule 2: Handle NULL DELIVERY_TIME WHEN DELIVERY_TIME IS NULL THEN 'PENDING' -- Rule 1: Delivery time is in the future relative to 2021-08-08 WHEN DELIVERY_TIME > '2021-08-08' THEN 'IN FUTURE' -- Rule 3: Check if this is the latest delivered record for the employee WHEN DELIVERY_TIME = MAX(CASE WHEN DELIVERY_TIME < '2021-08-08' THEN DELIVERY_TIME END) OVER (PARTITION BY Emp_ID) THEN 'DELIVERING' -- All other past records ELSE 'DELIVERED' END AS STATUS FROM Employee ORDER BY Emp_ID, DELIVERY_TIME DESC;
Explanation of the Query
Let's walk through each part to understand how it aligns with your rules:
- NULL Handling: The first
WHENclause directly addresses rule 2, marking any record withNULLdelivery time asPENDING. - Future Delivery Check: The second clause checks if the delivery date is after the fixed current date (
2021-08-08) and labels itIN FUTURE(rule 1). - Latest Past Delivery Identification:
- The subquery
MAX(CASE WHEN DELIVERY_TIME < '2021-08-08' THEN DELIVERY_TIME END) OVER (PARTITION BY Emp_ID)calculates the most recent delivery date that's before the current date, grouped by each employee. - We then compare the current record's
DELIVERY_TIMEto this maximum value: if they match, it's markedDELIVERING(rule 3), otherwise it'sDELIVERED.
- The subquery
- Ordering: The
ORDER BYclause is optional but helps visualize the results grouped by employee and sorted by delivery date, making it easier to verify the statuses.
Verification with Your Sample Data
When you run this query against your Employee table, it will produce exactly the output you provided:
| EMP_ID | DELIVERY_TIME | STATUS |
|---|---|---|
| E01 | 2022-08-21 | IN FUTURE |
| E01 | 2021-08-21 | IN FUTURE |
| E01 | 2021-08-07 | DELIVERING |
| E01 | 2021-05-21 | DELIVERED |
| E01 | 2019-08-21 | DELIVERED |
| E02 | 2023-08-21 | IN FUTURE |
| E02 | 2021-08-21 | IN FUTURE |
| E02 | 2021-08-06 | DELIVERING |
| E02 | 2021-06-21 | DELIVERED |
| E02 | 2020-08-21 | DELIVERED |
Key Improvements Over Your Attempt
- Simplified Nested Logic: Instead of multiple subqueries, we use a single window function to calculate the latest past delivery date directly in the
CASEstatement. - Correct Rule Prioritization: We handle
NULLfirst, then future dates, then the latest past record, ensuring all edge cases are covered. - Scalability: This query automatically supports new
Emp_IDvalues since thePARTITION BY Emp_IDclause dynamically groups each employee as they are added to the table.
内容的提问来源于stack exchange,提问作者Raghav
相关产品推荐
相关产品推荐

