How to add IF-THEN-ELSE logic to SQL and realize the conversion of ranks and columns?

In the previous article, we learned about the common date and time functions and type conversion functions in SQL. The proficient use of various functions can make our data processing and analysis work more effective.

In this article, we introduce a method for adding logic processing functions to SQL statements: CASE expressions.

CASE expressions in SQL can produce different results according to different conditions, and achieve logic functions similar to IF-THEN-ELSE in programming languages . For example, calculate the corresponding salary increase based on the employee's KPI, and evaluate the excellent, good, and pass according to the test results.

CASE expression supports two forms: simple CASE expression and search CASE expression .

Simple CASE expression

The syntax of a simple CASE expression is as follows:

CASE expression
  WHEN value1 THEN result1
  WHEN value2 THEN result2
  ...
  [ELSE default_result]
END

The calculation process of the expression is shown in the figure below:

![simple case](https://img-blog.csdnimg.cn/20190724163844995.png?x-oss-process=image/watermark,typeZmFuZ3poZW5naGVpdGk,shadow10,textaHR0cHM6Ly90b255ZG9uZy5ibG9nLmNzZG4ubmV0,size16,colorFFFFFF,t70#pic_center =660x)

First calculate the value of expression; then sequentially compare with the values ​​in the WHEN list (value1, value2, ...), find the first equal value and return the corresponding result (result

Guess you like

Origin blog.csdn.net/horses/article/details/108729107