select s.MountingsName as '品名',s.TypeSpecification as '规格',s.MaterialCode as '物料代码',s.Number as '库存数',
CASE
WHEN s.IsSafeStock=0 THEN '不满足'
WHEN s.IsSafeStock=1 THEN '满足'
END as '是否满足安全库存'
from CommonlyUsedAccessories as c left join Stock_Information as s on c.CuaId=s.MaterialCode
1.第一种写法:
SELECT
s.s_id,
s.s_name,
s.s_sex,
CASE
WHEN s.s_sex = '1' THEN '男'
WHEN s.s_sex = '2' THEN '女'
ELSE '其他'
END as sex,
s.s_age,
s.class_id
FROM
t_b_student s
WHERE
1 = 1
2.第二种写法
SELECT
s.s_id,
s.s_name,
s.s_sex,
CASE s.s_sex
WHEN '1' THEN '男'
WHEN '2' THEN '女'
ELSE '其他'
END as sex,
s.s_age,
s.class_id
FROM
t_b_student s
WHERE
1 = 1
两个运行结果一样:
有一个需要注意的问题,Case函数只返回第一个符合条件的值,剩下的Case部分将会被自动忽略
二:分组
表数据:
t_b_population
sql语句:
SELECT country,
SUM(CASE WHEN p.sex = '1' THEN p.population ELSE 0 END) AS '男',
SUM(CASE WHEN p.sex = '2' THEN p.population ELSE 0 END) AS '女'
FROM
t_b_population p
GROUP BY country;
运行结果:
表数据:
t_b_country
sql语句:
SELECT
SUM(c.population) AS '人口',
CASE c.country
WHEN '中国' THEN '亚洲'
WHEN '印度' THEN '亚洲'
WHEN '日本' THEN '亚洲'
WHEN '美国' THEN '北美洲'
WHEN '加拿大' THEN '北美洲'
WHEN '墨西哥' THEN '北美洲'
ELSE '其他' END AS '洲'
FROM
t_b_country c
GROUP BY CASE c.country
WHEN '中国' THEN '亚洲'
WHEN '印度' THEN '亚洲'
WHEN '日本' THEN '亚洲'
WHEN '美国' THEN '北美洲'
WHEN '加拿大' THEN '北美洲'
WHEN '墨西哥' THEN '北美洲'
ELSE '其他' END;
运行结果:
分类: 数据库