首先让我们看一下 case 的语法。在一般的 select 中,其语法如下:
select
case
when then
when then
else
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 都非常有用。再深入一步,你还可以得到你以前认为不可能得到的分组排序结果集。
本文来自 280文秘网(https://www.it280.com),转载请保留网址和出处
【探讨SQLServer中Case的不同用法】相关文章:
爱我中华02-10
中考英语作文:节约用水02-10
分式的乘方和乘方法则02-10
美国留学工作签证对理科类专业的政策倾斜02-10
四年级满分作文200字:绿色在我手中02-10
分式的乘方和乘方法则02-10
初中生过新年作文700字02-10
哥哥的作文02-10
适合三年级小学生的英语期末测试题02-10
漠河的冬天02-10
观察鱼的作文02-10
