Answer: Common Table Expressions
Explore how to use common table expressions with CASE expressions to classify suppliers by risk level and filter results using SQL. This lesson helps you understand building reusable and readable queries to handle complex data classifications and custom sorting in MySQL.
Solution
The solution is given below:
Explanation
The explanation of the solution code is given below:
Line 1: This starts a common table expression with
WITH SupplierPerformance AS (...). This defines a named temporary result set calledSupplierPerformancethat is only visible to the mainSELECTthat follows.Line 2: This uses
SELECTto list all required columns from the base table in one line:SupplierID,SupplierName,OnTimeDeliveryRate, andAvgLeadTime. These are the core supplier identifiers and delivery metrics that the CTE will work with.Lines 3–7: These introduce a
CASEexpression that classifies each supplier into a risk category:Line 4: If
OnTimeDeliveryRateis less than96orAvgLeadTimeis greater than5, the supplier is labeled'High'risk.Lines 5–6: If
OnTimeDeliveryRateis between96and97.99andAvgLeadTimeis between4and5, the supplier is labeled'Medium'risk.Line 7: All remaining suppliers are classified as
'Low'risk by theELSEbranch. ...