《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;

很神奇的脑洞。

猜你喜欢

转载自www.cnblogs.com/qianbixin/p/10251472.html