sql select case when语句用法实例

发布时间:2020-04-09编辑:脚本学堂
有关sql select case when语句的用法,在sql数据库中case when语句的多种用法,不了解的朋友参考下。

本节重点介绍select case when语句的一般用法,case when语句与group by子句结合的用法,可以组合这些选项并添加order by子句的用法等。

case 可能是 sql 中被误用最多的关键字之一。

例如,可以在 where 子句中使用 case。

case 的语法。

在一般的 select 中,其语法如下:
select <mycolumnspec> =
case
when <a> then <somethinga>
when <b> then <somethingb>
else <somethinge>
end 
以上代码中,需要用具体的参数代替尖括号中的内容。

例子:
 

复制代码 代码示例:
use pubs
go
select
title,
'price range' =
case
when price is null then 'unpriced'
when price < 10 then 'bargain'
when price between 10 and 20 then 'average'
else 'gift to impress relatives'
end
from titles
order by price
go 

这是 case 的典型用法,但是使用 case 其实可以做更多的事情。

例子,group by 子句中的 case:
 

复制代码 代码示例:
select 'number of titles', count(*)
from titles
group by
case
when price is null then 'unpriced'
when price < 10 then 'bargain'
when price between 10 and 20 then 'average'
else 'gift to impress relatives'
end
go 

还可以组合这些选项,添加一个 order by 子句。

例子:
 

复制代码 代码示例:
use pubs
go
select
case
when price is null then 'unpriced'
when price < 10 then 'bargain'
when price between 10 and 20 then 'average'
else 'gift to impress relatives'
end as range,
title
from titles
group by
case
when price is null then 'unpriced'
when price < 10 then 'bargain'
when price between 10 and 20 then 'average'
else 'gift to impress relatives'
end,
title
order by
case
when price is null then 'unpriced'
when price < 10 then 'bargain'
when price between 10 and 20 then 'average'
else 'gift to impress relatives'
end,
title
go 
 

注意,为了在 group by 块中使用 case,查询语句需要在 group by 块中重复 select 块中的 case 块。
除了选择自定义字段之外,在很多情况下 case 都非常有用。

当然,还可以得到分组排序结果集等。