租用问题

质量为本、客户为根、勇于拼搏、务实创新

< 返回租用问题列表

sql casewhen语句如何使用,sql语句中case when用法

发布时间:2023-11-15 00:50:48

sql casewhen语句如何使用

CASE WHEN语句用于根据条件履行区分的操作或返回区分的值。它的基本语法以下:

CASE
    WHEN condition1 THEN result1
    WHEN condition2 THEN result2
    ...
    ELSE default_result
END

其中,condition1、condition2等是条件表达式,result1、result2等是对应条件为真时的返回结果,default_result是当没有条件满足时的默许返回结果。

下面是一个例子,演示了怎样使用CASE WHEN语句:

假定有一个名为"employees"的表,其中包括"first_name"和"last_name"列。现在需要根据员工的"first_name"和"last_name"显示区分的称谓,如果"first_name"是"John",“last_name"是"Doe”,则显示"Mr. Doe",否则显示"Ms. {last_name}"。

SELECT 
    CASE 
        WHEN first_name = 'John' AND last_name = 'Doe' THEN 'Mr. Doe'
        ELSE CONCAT('Ms. ', last_name)
    END AS title
FROM 
    employees;

这个例子中,CASE WHEN语句根据"first_name"和"last_name"的值决定返回的称谓。如果"first_name"是’John’且"last_name"是’Doe’,则返回结果为"Mr. Doe",否则返回结果为"Ms. {last_name}"。