create DATABASE advanced_prac;
use advanced_prac;
CREATE TABLE bonuses_depa1 (--旧奖金表
staff_id INT NOT NULL, --员工id
staff_name CHAR(50), --员工名字
job VARCHAR(30),--员工岗位
bonus NUMERIC );--津贴
CREATE TABLE new_bonuses_depa1 (--新奖金表
staff_id INT NOT NULL,
staff_name CHAR(50),
job VARCHAR(30),
bonus NUMERIC );
插入数据
旧表
INSERT INTO bonuses_depa1(staff_id, staff_name, job, bonus) VALUES(23,'wangxia','developer',5000);
INSERT INTO bonuses_depa1(staff_id, staff_name, job, bonus) VALUES(24,'limingying','tester',7000);
INSERT INTO bonuses_depa1(staff_id, staff_name, job, bonus) VALUES(25,'liulili','quality control', 8000);
INSERT INTO bonuses_depa1(staff_id, staff_name, job, bonus) VALUES(29,'liuxue','tester',8000);
INSERT INTO bonuses_depa1(staff_id, staff_name, job, bonus) VALUES(21,'caoming','document developer',11000);
新表
INSERT INTO new_bonuses_depa1(staff_id, staff_name, job, bonus) VALUES(23,'wangxia','developer', 7000);
INSERT INTO new_bonuses_depa1(staff_id, staff_name, job, bonus) VALUES(27,'wangxuefen','document developer',7000);
INSERT INTO new_bonuses_depa1(staff_id, staff_name, job, bonus) VALUES(28,'denghui','quality control',8000);
INSERT INTO new_bonuses_depa1(staff_id, staff_name, job, bonus) VALUES(25,'liulili','quality control',10000);
INSERT INTO new_bonuses_depa1(staff_id, staff_name, job, bonus) VALUES(21,'caoming','document developer',12000);
查询表bonuses_depa1中的数据。
SELECT * FROM bonuses_depa1;
返回结果:
查询表new_bonuses_depa1中的数据。
SELECT * FROM new_bonuses_depa1;
case表达式的返回类型是所有返回值的兼容聚合类型,而且取决于使用它的上下文。如果在上下文中使用字符串,结果将返回为字符串。如果在上下文中使用数字,结果返回为十进制、实数或整数值。
CASE value WHEN [compare_value] THEN result [WHEN [compare_value] THEN result ...][ELSE result] END
要求:当compare_value被满足时,返回对应的result,否则返回ELSE语句后的result,如果没有ELSE语句,则返回NULL
查询bonuses_depa1表,如果staff_name为“wangxia”则输出漂亮,如果staff_name为“liulili”则输出愚蠢,其余输出“普通”。
sql语句
SELECT bd.STAFF_NAME,--查询项
CASE bd.STAFF_NAME --比较的项
WHEN 'wangxia' THEN '漂亮'--如果是“wangxia”输出“漂亮”
WHEN 'liulili' THEN '愚蠢'--如果是“liulili”输出“愚蠢”
ELSE '普通' --其余输出普通
END AS EVALUATE --输出项别名
FROM bonuses_depa1 bd; --查询的表以及起的别名
CASE WHEN [condition] THEN result [WHEN [condition] THEN result ...][ELSE result] END
当condition被满足时,返回对应的result,否则返回ELSE语句后的result,如果没有ELSE语句,则返回NULL
要求:比较两表new_bonuses_depa1和bonuses_depa1的津贴数据,对比员工津贴变化情况。
sql语句
SELECT bd.STAFF_NAME, --查询此表项
CASE --case语句开始
WHEN nbd.BONUS > bd.BONUS THEN 'increased' --如果nbd.BONUS > bd.BONUS时输出'increased'
WHEN nbd.BONUS = bd.BONUS THEN 'equal' --如果nbd.BONUS = bd.BONUS时输出'equal'
ELSE 'decreased' --否则输出'decreased'
END AS DIFF --case语句结束,并将输出结果列取别名DIFF
FROM new_bonuses_depa1 nbd, bonuses_depa1 bd --分别给两个表起别名
WHERE nbd.STAFF_ID = bd.STAFF_ID--两表联系条件(员工id相同)