【學習點點滴滴】 要對case when then 的用法進行說明,我認爲我們弄清case 的兩種用法即可,當然只是淺析,在此也感謝CSDN裏的兄弟給我的解答。下面建個表,運用case when then 語句 對錶進行一系列的處理,得到我們想要的結果。來進行說明:
(1):建一個表:
create table ta ([姓名] varchar(10),[課程] varchar(4),[分數] int)
insert ta
select 'sinpoal','語文',85 union all
select 'sinpoal','數學',90 union all
select 'sinpoal','物理',70 union all
select 'sinpoal1','數學',80 union all
select 'sinpoal1','物理',60 union all
select 'sinpoal1','語文',79 union all
select 'sinpoal2','數學',98 union all
select 'sinpoal2','物理',80 union all
select 'sinpoal2','語文',72
--第一步
select 姓名,
case when 課程='語文' then 分數 end 語文,
case when 課程='數學' then 分數 end 數學,
case when 課程='物理' then 分數 end 物理
from ta
/*
姓名 語文 數學 物理
---- ----------- ----------- -----------
sinpoal 85 NULL NULL
sinpoal NULL 90 NULL
sinpoal NULL NULL 70
sinpoal1 NULL 80 NULL
sinpoal1 NULL NULL 60
sinpoal1 79 NULL NULL
sinpoal2 NULL 98 NULL
sinpoal2 NULL NULL 80
sinpoal2 72 NULL NULL
--第二步
--(第一種用法)
select 姓名 ,
max(case 課程 when '語文' then 分數 end ) 語文,
max(case 課程 when '數學' then 分數 end) 數學,
max(case 課程 when '物理' then 分數 end) 物理
from ta
group by 姓名
--(第二種用法)
select 姓名 ,
max(case when 課程= '語文' then 分數 end ) 語文,
max(case when 課程='數學' then 分數 end) 數學,
max(case when 課程= '物理' then 分數 end) 物理
from ta
group by 姓名
/*
姓名 語文 數學 物理
---- ----------- ----------- -----------
sinpoal 85 90 70
sinpoal1 79 80 60
sinpoal2 72 98 80
姓名 語文 數學 物理
---- ----------- ----------- -----------
sinpoal 85 90 70
sinpoal1 79 80 60
sinpoal2 72 98 80
可以看到兩種用法對結果沒有影響,但值得一說的是,後者可以加條件*/