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

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

哈爾濱 函數 ast mas alt 情況 tmp lse rac

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;

很神奇的腦洞。

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