在 SQL 中,CASE WHEN
語句可以幫助我們根據特定條件對數據進行處理
當有多個條件需要判斷時,可以使用嵌套的 CASE WHEN
語句來簡化查詢。例如,假設我們有一個銷售表,需要根據銷售額來判斷銷售情況:
SELECT
sales_id,
CASE
WHEN sales_amount < 1000 THEN 'Low'
WHEN sales_amount >= 1000 AND sales_amount < 5000 THEN 'Medium'
ELSE 'High'
END AS sales_level
FROM sales;
嵌套的 CASE WHEN
語句還可以用于計算字段值。例如,假設我們需要計算每個銷售人員的提成,根據銷售額和銷售人員的級別來計算:
SELECT
salesperson_id,
sales_amount,
CASE
WHEN sales_amount < 1000 THEN sales_amount * 0.05
WHEN sales_amount >= 1000 AND sales_amount < 5000 THEN sales_amount * 0.1
ELSE sales_amount * 0.15
END AS commission
FROM sales;
當需要根據多個條件組合來計算字段值時,可以使用嵌套的 CASE WHEN
語句。例如,假設我們需要計算每個銷售人員的獎金,根據銷售額和銷售人員的級別來計算:
SELECT
salesperson_id,
sales_amount,
CASE
WHEN sales_amount < 1000 AND salesperson_level = 'Junior' THEN sales_amount * 0.03
WHEN sales_amount < 1000 AND salesperson_level = 'Senior' THEN sales_amount * 0.04
WHEN sales_amount >= 1000 AND sales_amount < 5000 AND salesperson_level = 'Junior' THEN sales_amount * 0.08
WHEN sales_amount >= 1000 AND sales_amount < 5000 AND salesperson_level = 'Senior' THEN sales_amount * 0.1
ELSE sales_amount * 0.12
END AS bonus
FROM sales;
總之,嵌套的 CASE WHEN
語句可以幫助我們更簡潔地處理復雜的條件判斷和計算。在實際應用中,可以根據需求靈活地使用嵌套的 CASE WHEN
語句。