sql中的case when的用法

来源:互联网 发布:金科信软件 编辑:程序博客网 时间:2024/05/20 07:19

CASE有两种用法

      一种是CASE简单表达式用法

         for example:

                      CASE sex 

                      WHEN  '1'  THEN  '男'

                       WHEN '2'   THEN '女'

                       ELSE  '其他'

                      END

     另外一种是CASE搜索表达式的用法

       for example:

                  CASE WHEN sex='1'  THEN '男'

                              WHEN sex='2'  THEN '女'

                             ELSE  '其他'

                           END

两种CASE函数的ELSE都是可选的,可有可无。另外CASE WHEN用法也可以用在order by,group by语句中。

下面我们来看一道题目,假设表一是Student表,用一句Sql得到第二张表的效果?

select Sname,IsNull(Sum(Case Ssubject when '语文' then Sscores end),0) '语文',IsNull(Sum(Case Ssubject when '数学' then Sscores end),0) '数学',IsNull(Sum(case Ssubject when '物理'  then Sscores end),0) '物理',IsNull(Sum(case Ssubject when '化学' then Sscrores end),0) '化学' from Student group by Sname

0 0
原创粉丝点击