CASE WHEN 是 SQL 查詢中的一個條件表達式,它允許你根據一個或多個條件返回不同的值
以下是 CASE WHEN 在 SQL 查詢中的一些實際應用:
SELECT
student_id,
student_name,
score,
CASE
WHEN score >= 90 THEN 'A'
WHEN score >= 80 THEN 'B'
WHEN score >= 70 THEN 'C'
WHEN score >= 60 THEN 'D'
ELSE 'F'
END AS grade
FROM students;
SELECT
employee_id,
employee_name,
years_of_experience,
CASE
WHEN years_of_experience < 3 THEN 'Junior'
WHEN years_of_experience >= 3 AND years_of_experience < 5 THEN 'Intermediate'
ELSE 'Senior'
END AS experience_level
FROM employees;
SELECT
customer_id,
customer_name,
total_spending,
CASE
WHEN total_spending >= 10000 THEN 'VIP'
WHEN total_spending >= 5000 AND total_spending < 10000 THEN 'Regular'
ELSE 'New Customer'
END AS customer_type
FROM customers;
SELECT
order_id,
order_date,
order_status,
CASE
WHEN order_status = 'Shipped' THEN 'Your order has been shipped.'
WHEN order_status = 'Processing' THEN 'Your order is being processed.'
WHEN order_status = 'Cancelled' THEN 'Your order has been cancelled.'
ELSE 'Your order status is unknown.'
END AS order_message
FROM orders;
這些示例展示了如何使用 CASE WHEN 在 SQL 查詢中根據不同的條件返回特定的值。這可以幫助你根據數據庫中的數據創建更復雜的查詢和報告。