首頁  >  文章  >  資料庫  >  sqlserver中case when用法小结

sqlserver中case when用法小结

WBOY
WBOY原創
2016-06-07 16:19:194802瀏覽

首先建表和插入数据语句: use Student go create table Score ( 学号 nvarchar(10), 课程 nvarchar(10), 成绩 int ) go insert into Score values('0001','语文',87); insert into Score values('0001','数学',79); insert into Score values('0001','英语'

   首先建表和插入数据语句:

  use Student

  go

  create table Score

  (

  学号 nvarchar(10),

  课程 nvarchar(10),

  成绩 int

  )

  go

  insert into Score values('0001','语文',87);

  insert into Score values('0001','数学',79);

  insert into Score values('0001','英语',95);

  insert into Score values('0002','语文',69);

  insert into Score values('0002','数学',84);

  insert into Score values('0001','语文',95);

  case when 用法一:

  CASE 简单表达式,它通过将表达式与一组简单的表达式进行比较来确定结果。

  select 学号,

  sum(case when 课程='语文' then 成绩 else 0 end ) as 语文,

  sum(case when 课程='数学' then 成绩 else 0 end ) as 数学,

  sum(case when 课程='英语' then 成绩 else 0 end ) as 英语

  from Score

  group by 学号

  case when 用法二:

  CASE 搜索表达式,它通过计算一组布尔表达式来确定结果。

  select 学号,成绩,

  case 成绩

  when 87 then '良'

  when 79 then '良'

  when 95 then '优'

  when 69 then '中'

  else '差' end as test

  from Score

  上面为本人对case when的理解,,如有错误希望批评指出,多谢!

  注:每个case 对应一列数据

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn