1. 程式人生 > >《SQL進階教程》抄書筆記01-case表示式

《SQL進階教程》抄書筆記01-case表示式

 

1.1 區域人口總數統計

  轉換成 

-- 注意group by後跟的條件
select
case pref_name when '北京' then '北方' when '哈爾濱' then '北方' when '廣州' then '南方' when '深圳' then '南方' else '其他' end as district, sum(population) as total from poptbl group by case pref_name when '北京' then
'北方' when '哈爾濱' then '北方' when '廣州' then '南方' when '深圳' then '南方' else '其他' end

1.2 行統計轉為列統計

轉換為

select pref_name, 
    sum(case when sex=1 then population else 0 end) as male,  -- 注意使用了sum函式
    sum(case when sex=2 then population else 0 end) as female
from poptbl2
group by pref_name

1.3 在update語句裡面進行條件分支

將下表作如下操作: 1. 對當前工資為 30 萬日元以上的員工,降薪 10%。 2. 對當前工資為 25 萬日元以上且不滿 28 萬日元的員工,加薪20%。 變為 分析:如果1和2寫成兩個sql語句分別執行,則李四會先降薪再加薪,導致出錯,可以用case語句對不同的條件進行分別處理,一次完成。
update salaries 
set salary = case 
    when salary >= 300000 then salary*
0.9 when salary >= 250000 and salary < 280000 then salary*1.2 else salary end; -- 注意一定要寫else,否則不在上述條件裡面的工資會被置為NULL

1.4 生成課程表

==> 分析:自己體會
select course_name,
  case when exists (
    select * from opencourses OC where CM.course_id = OC.course_id and OC.month = '200706'
  ) then 'o' else 'x' end as '6月',
  case when exists (
    select * from opencourses OC where CM.course_id = OC.course_id and OC.month = '200707'
  ) then 'o' else 'x' end as '7月',
  case when exists (
    select * from opencourses OC where CM.course_id = OC.course_id and OC.month = '200708'
  ) then 'o' else 'x' end as '8月'
from coursemaster CM

1.5 case表示式使用聚合函式

這是一個學生參加社團情況的表,如果一個學生參加了一個社團,他的main_club_flg是N,如果參加了多個社團,他的主社團的main_club_flg是Y,其餘的都是N。 要求: 1.獲取只加入了一個社團的學生的社團ID, 2.獲取加入多個社團的學生的主社團ID 解法1:
-- 先查出只加入了一個社團的學生的社團ID
select std_id, max(club_id) from studentclub
group by std_id
having count(*) = 1
-- 再查出有主社團標誌的社團ID
select std_id, club_id
from studentclub
where main_club_flg = 'Y'

解法2:使用case表示式,一個sql即可完成

-- select後跟的欄位,要麼是分組欄位,要麼被包含到聚合函式中
-- 聚合函式計算某個欄位時自動忽略null行
select std_id,
case when count(*)=1
then max(club_id)
else max(case when main_club_flg='Y' then club_id else null end)
end as main_club
from studentclub
group by std_id

1.6 求行的極值

x列的最大值可以用max(x)求出來,A行的最大值怎麼求出來呢? ==》   解法1:用mysql或者oracle的greatest函式
select `key`, greatest(x,y,z) as max
from greatests

 解法2:用case表示式

select `key`,
case when x < y then (case when y < z then z else y end)
else (case when x < z then z else x end)
end as max
from greatests

解法3:行列轉換後使用max函式

SELECT `key`, MAX(col) AS greatest
FROM (
SELECT `key`, x AS col FROM Greatests
UNION ALL
SELECT `key`, y AS col FROM Greatests
UNION ALL
SELECT `key`, z AS col FROM Greatests
)TMP
GROUP BY `key`;

1.7 自定義order by

執行sql語句
select `key` from greatests
order by `key`

得到結果如下

,修改sql語句使其變成這樣:   解法:
select `key` from greatests
order by case
when `key`='B' then 1
when `key`='A' then 2
when `key`='D' then 3
when `key`='C' then 4
else null end;

很神奇的腦洞。