case when then else end 进行空值判断
时间: 2024-12-19 11:18:06 浏览: 6
`CASE WHEN THEN ELSE END` 是 SQL 中的一种条件表达式结构,常用于进行空值(NULL)判断和数据的条件处理。这个语法通常在 `SELECT` 语句中使用,其基本结构如下:
```sql
CASE
WHEN condition THEN result_if_true
ELSE result_if_false
END
```
在这里:
- `condition` 是你要测试的条件,如果为真,则执行 `THEN` 部分;
- `result_if_true` 如果条件成立,返回的结果会是这个部分的内容;
- `result_if_false` (可选)如果 `condition` 为假(即为空值),则返回这个部分的内容。
举个例子,如果你想检查某个字段是否为空,你可以这样写:
```sql
SELECT
CASE
WHEN column_name IS NULL THEN 'Value is NULL'
ELSE column_name
END
FROM table_name;
```
这将返回 `column_name` 的值,如果它为空,则显示 "Value is NULL"。
相关问题
SELECT * FROM emm_task.tbl_scm_passenger ORDER BY CASE WHEN id IN (53213970,53213971,53213972,53213973,53213974,53213975,53213976,53213977,53213978,53213979,53213980,53213981,53213982,53213983,53213984,53213985,53213986,53213987,53213988,53213989) then 0 ELSE 1 END, CASE WHEN phone IS NULL THEN 1 WHEN id IN (53213970,53213971,53213972,53213973,53213974,53213975,53213976,53213977,53213978,53213979,53213980,53213982,53213983,53213984,53213985,53213986,53213987,53213988,53213989) THEN 0 ELSE 2 END, phone ASC, CASE WHEN id IN (53213970,53213971,53213972,53213973,53213974,53213975,53213976,53213977,53213978,53213979,53213980,53213982,53213983,53213984,53213985,53213986,53213987,53213988,53213989) THEN mobile END, CASE WHEN mobile IS NULL THEN 1 ELSE 0 END想让mobile排序的时候空值在下面排序
您的查询语句已经实现了 mobile 的排序,并将空值排在了 mobile 值的后面。如果您想要让 mobile 的空值排在 mobile 值的前面,则可以将这一部分代码:
CASE WHEN mobile IS NULL THEN 1 ELSE 0 END
修改为:
CASE WHEN mobile IS NULL THEN 0 ELSE 1 END
这样一来,空值就会优先于非空值进行排序。完整的修改后的查询语句如下所示:
SELECT * FROM emm_task.tbl_scm_passenger
ORDER BY
CASE WHEN id IN (53213970,53213971,53213972,53213973,53213974,53213975,53213976,53213977,53213978,53213979,53213980,53213981,53213982,53213983,53213984,53213985,53213986,53213987,53213988,53213989) THEN 0 ELSE 1 END,
CASE WHEN phone IS NULL THEN 1 WHEN id IN (53213970,53213971,53213972,53213973,53213974,53213975,53213976,53213977,53213978,53213979,53213980,53213982,53213983,53213984,53213985,53213986,53213987,53213988,53213989) THEN 0 ELSE 2 END,
CASE WHEN id IN (53213970,53213971,53213972,53213973,53213974,53213975,53213976,53213977,53213978,53213979,53213980,53213982,53213983,53213984,53213985,53213986,53213987,53213988,53213989) THEN mobile END,
CASE WHEN mobile IS NULL THEN 0 ELSE 1 END,
phone ASC;
sql 用case when 判断空值
在SQL中,可以使用CASE WHEN语句来判断空值。CASE WHEN语句是一种条件表达式,它允许根据条件的不同返回不同的结果。
下面是使用CASE WHEN语句判断空值的示例:
```sql
SELECT column1, column2,
CASE WHEN column3 IS NULL THEN '空值' ELSE '非空值' END AS is_null
FROM your_table;
```
在上面的示例中,我们使用了CASE WHEN语句来判断column3是否为空值。如果column3为空值,则返回'空值',否则返回'非空值'。你可以根据实际需求修改返回的结果。
阅读全文