SQL中的CASE WHEN語句在報表中的應用非常廣泛,可以用來根據特定的條件對數據進行分類、篩選和計算。以下是一些在報表中使用SQL CASE WHEN語句的技巧:
SELECT
product_name,
sales,
CASE
WHEN sales > 1000 THEN 'High'
WHEN sales > 500 THEN 'Medium'
ELSE 'Low'
END AS sales_level
FROM products;
SELECT
product_name,
sales
FROM products
WHERE
CASE
WHEN sales > 1000 THEN 1
ELSE 0
END = 1;
SELECT
product_name,
sales,
CASE
WHEN sales > 0 THEN profit / sales
ELSE 0
END AS profit_margin
FROM products;
SELECT
product_name,
sales,
CASE
WHEN region = 'North' THEN sales * 0.1
WHEN region = 'South' THEN sales * 0.2
ELSE sales * 0.15
END AS discount
FROM products;
總的來說,SQL CASE WHEN語句在報表中的應用非常靈活,可以根據實際需求進行各種條件判斷、分類和計算,幫助我們更好地分析和理解數據。