CASE WHEN 语法怎么用
时间: 2024-05-28 20:07:08 浏览: 107
Case_When用法
CASE WHEN语法是SQL中的一种条件表达式语法,通常用于在查询中进行条件判断和结果分组,它的基本语法如下:
```
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
...
WHEN conditionN THEN resultN
ELSE default_result
END
```
其中,`condition1`到`conditionN`是条件表达式,`result1`到`resultN`是满足条件时的结果,`default_result`是当所有条件都不满足时的默认结果。
例如,以下查询将对销售额进行分组,并且将销售额按照一定区间进行分组:
```
SELECT
CASE
WHEN sales_amount <= 1000 THEN '0-1000'
WHEN sales_amount > 1000 AND sales_amount <= 2000 THEN '1000-2000'
WHEN sales_amount > 2000 AND sales_amount <= 3000 THEN '2000-3000'
ELSE '3000以上'
END AS sales_range,
SUM(sales_amount) AS total_sales
FROM
sales_table
GROUP BY
CASE
WHEN sales_amount <= 1000 THEN '0-1000'
WHEN sales_amount > 1000 AND sales_amount <= 2000 THEN '1000-2000'
WHEN sales_amount > 2000 AND sales_amount <= 3000 THEN '2000-3000'
ELSE '3000以上'
END;
```
以上查询语句将根据销售额将数据分组,并统计每个分组的总销售额,最终的结果类似于:
```
sales_range | total_sales
-----------
0-1000 | 10000
1000-2000 | 15000
2000-3000 | 8000
3000以上 | 5000
```
阅读全文