SQL中关于case关键字的例子(行列转换)

来源:互联网 发布:互动投影软件设置 编辑:程序博客网 时间:2024/05/31 05:28

case关键字用法类似于C#、Java中的switch...case...的用法:

select name,

(

case express--列名(表达式)

when... then...--当express等于..., ...

when... then,,,--当express等于..., ...

else --那么...

end

)

接着看下面例子。

 

 

 

数据表中的数据:

 

                     date               name score

2011-02-19 17:38:45.813     拜仁  

2011-02-19 17:38:45.813     奇才   胜

2011-02-19 17:38:45.813     湖人   胜

2011-02-19 17:38:45.813     拜仁   负 

2011-02-19 17:38:45.813     拜仁   负

2011-02-19 17:38:45.813     奇才   胜

 

 

 

需要显示的效果:

 

name   胜   负

  拜仁   1    2

  湖人   1    0

  奇才   2    0

 

 

 

SQL语句:(第一步)

 

 

select name,

(

case score

when N'胜' then 1

else 0

end

)as 胜,

(

case score

when N'负' then 1

else 0

end

)as 负

from test

 

 

第一步显示效果:

name   胜   负

 

  拜仁   1     0

  奇才   1     0

  湖人   1     0

  拜仁   0     1

  拜仁   0     1

  奇才   1     0

 

 

SQL语句:(第二步)

 

select name,

sum(

case score

when N'胜' then 1

else 0

end

)as 胜,

sum(

case score

when N'负' then 1

else 0

end

)as 负

from test

group by name

 

 

第二步显示结果:

 

name    胜   负

  拜仁     1    2

  湖人     1    0

  奇才     2    0

 

 

原创粉丝点击