目录
1.基础查询
-- 1. 查询职员表中工资大于 3600 的员工姓名和工资
select ename, sal from emp where sal > 3600;
-- 2. 查询职员表中员工号为 7369 的员工的姓名和部门号码
select ename, deptno from emp where empno = 7369;
-- 3. 选择职员表中工资不在 4000 到 5000 的员工的姓名和工资
select ename, sal from emp where sal not between 4000 and 5000;
-- 4. 选择职员表中在 20 和 30 号部门工作的员工姓名和部门号
select ename, deptno from emp where deptno in(20, 30);
-- 5. 选择职员表中没有管理者的员工姓名及职位,按职位排序
-- 6. 选择职员表中有奖金的员工姓名,工资和奖金,按工资倒序排列
select ename, sal, comm from emp where comm is not null order by sal desc;
-- 7. 选择职员表中员工职位的第二个字母是 a 的员工姓名
select ename from emp where ename like '_A%';
-- 8. 查询那些尚未分配部门的员工的姓名 where deptno is null
-- 9. 列出部门表中的部门名字和所在城市;
-- 10. 显示出职员表中的不重复的职位;
select distinct job from emp;
-- 11. 连接职员表中的职员名字、职位、薪水,列之间用逗号连接,列头显示成 OUT_PUT
select concat(ename, ",", job, ",", sal) OUT_PUT from emp;
select concat("str1", ",", "str2", ",", "str3");
-- 函数嵌套
select concat(concat("str1", ","),"str2");
-- 12. 查询职员表 emp 中员工号、姓名、工资,以及工资提高百分之 20%后的结果,元为单位进行四舍五入
select empno, ename, sal, round(sal * 1.2) from emp;
select round(35.14, -1); -- 40
-- 13. 查询员工的姓名和工资数,条件限定为工资数必须大于 3200,并对查询结果按入职时间进行排序,早入职排在前面,晚入职排在后面。
select ename, sal from emp where sal > 3200 order by hiredate;
-- 14. 列出部门表中除了 ACCOUNT 部门还有哪些部门。 where dname <> 'ACCOUNT'
-- 15. 已知员工的收入为:薪资+绩效*0.8,如果绩效为null,则表示绩效为0。查询员工的姓名以及月收入(列名为money),并按照月收入升序排序
select ename, sal + ifnull(comm,0) * 0.8 money from emp order by money;
select if(12,0,1);
select ifnull(null,0);
-- 16. 将员工的姓名按首字母排序,并列出姓名的长度(length)
select ename,length(ename) from emp order by ename;
-- 17. 查询各员工的姓名 ename,并显示出各员工在公司工作的月份数 (即:和当前日期比较,该员工已经工作了几个月, 用整数表示)。
select ename, timestampdiff(month, hiredate, now()) from emp;
/**
18.现有数据表 Customer,其结构如下所示:
cust_id int(4) Primary Key, --客户编码
cname VARCHAR(25) Not Null, --客户姓名
birthday DATE, --客户生日
account int. --客户账户余额
1) 构造 SQL 语句,列出 Customer 数据表中每个客户的信息。如果客户生日未提供,则该列值显示“not available” 。如果没有余额信息,则显示“no account”。
2) 构造 SQL 语句,列出生日在 1987 年的客户的全部信息。
3) 构造 SQL 语句,列出客户帐户的余额总数。
*/
create table Customer (
cust_id int(4) Primary Key,
cname VARCHAR(25) Not Null,
birthday DATE,
account int
);
select cust_id, cname, if(birthday,birthday,"not available"),
ifnull(account,"no account") from Customer;
select * from Customer where YEAR(birthday) = 1987;
select month(now());
select day(now());
-- 22.查询员工的姓名和工资,按下面的形式显示:(提示:使用 lpad 函数)
select ename, lpad(sal,15,"$") from emp;
-- 结果排序 order by [数值\时间\字符串]
-- 默认 asc 升序
-- desc 降序