CASE expression is used to determine the condition returns a value when the condition is satisfied, another value is returned when the condition is not satisfied.
grammar:
CASE WHEN ... THEN ...
WHEN ... THEN ...
ELSE ...
END
(Note: The data type of each of the branches back must be the same.)
(Note: when exclusivity clause must be, because when the when clause is true, when the remaining clauses will be ignored.)
CASE
WHEN ComparsionCondition THEN result
WHEN ComparsionCondition THEN result
ELSE other
END
CASE expression uses:
1, the conventional coding method conversion
example:
student_name score Ming 80 Red 92 Huzi 100 Mung 60
Score student_name
Ming good
Red preferably
Huzi preferably
Mung in
SELECT student_name, (CASE WHEN score>=90 THEN '优' WHEN score<90 AND score>=75 THEN '良' WHEN score<75 AND score>=60 THEN '中' ELSE '不及格' END) AS score FROM Score;
2, Cross-Tab Construction
example:
The Result DATE 1900-1-1 wins 1900-1-1 wins 1900-1-1 negative 1900-1-2 wins 1900-1-2 wins
Outcome
1900-1-121
1900-1-2 2 0
SELECT DISTINCT Date, SUM(CASE WHEN Result='胜' THEN 1 ELSE 0 END) AS '胜', SUM(CASE WHEN Result='负' THEN 1 ELSE 0 END) AS '负' FROM Test GROUP BY Date;
3, the ranks of the converted
product_type sum_price clothes 5000 office 600 kitchen 10000
sum_price_clothes sum_price_office sum_price_kitchen
5000 600 10000
SELECT SUM(CASE WHEN product_type = '衣服' THEN sale_price ELSE 0 END) AS sum_price_clothes, SUM(CASE WHEN product_type = '办公用品' THEN sale_price ELSE 0 END) AS sum_price_office, SUM(CASE WHEN product_type = '厨房用品' THEN sale_price ELSE 0 END) AS sum_price_kitchen FROM Product;
4, generate a specific ordering
Examples: The table of the sorted sequence B, D, C, A of the
item xyz A 1 2 3 B 5 5 2 C 4 7 1 D 3 3 8
SELECT item, x, y, z FROM t ORDER BY ( CASE WHEN item="B" THEN 1 WHEN item="D" THEN 2 WHEN item="C" THEN 3 WHEN item="A" THEN 4 ELSE NULL END );