以SCOTT用户为例
1、查询SCOTT用户拥有哪些表
selecttable_namefromuser_tables;
2、查询dept表的所有内容
selectfromdept;
3、查询dept的表结构
descdept;
4、在dept中增加y一条数据
insertintodept(deptno,dname,loc)values(50,''Development'',''Beijing'');
commit;
注:commit是把插入的数据提交到数据库中,如果没有commit,则插入的SQL语句是在计算机的内存中,如果遇上断电故障,出入的数据有可能不会存储在数据库中。
5、更新dept的数据
updatedeptsetloc=''Shanghai''wheredeptno=50;
commit;
6、在dept中删除一条数据
deletefromdeptwheredeptno=50;
commit;
7、设置查询数据的时间格式
中国时间格式:
altersessionsetnls_date_format=''YYYY-MM-DD'';
8、查询当前数据库的时间
selectsysdatefromdual;
注:在查询日期时,sysdate是数据库当前的日期,dual是oracle数据库的一个虚表,即不是一个真实存在的表,在查询用到计算、常量表达式等时可以使用的dual虚表
9、查询每个员工在公司的工作时间
selectename,round((sysdate-hiredate)/365,0)fromemp;
注:round(X,Y):是Oracle数据库的一个四舍五入的函数,X表示需要进行四舍五入的数,Y表示在哪位上进行四舍五入,如果Y=0表示在个位上进行四舍五入,Y=2表示在小数点后两位进行四舍五入。
10、查询每个员工在公司的工作时间,按年数排序
selectename,round((sysdate-hiredate)/365,0)fromemporderbyround((sysdate-hiredate)/365,0);
或selectename,round((sysdate-hiredate)/365,0)fromemporderby2;
注:orderby是排序关键字,2表示按照第二列排序,在这里ename是第一列,round((sysdate-hiredate)/365,0)是第二列,默认按照升序排序。
降序排序:
selectename,round((sysdate-hiredate)/365,0)fromemporderbyround((sysdate-hiredate)/365,0)desc;
或selectename,round((sysdate-hiredate)/365,0)fromemporderby2desc;
11、变成中文列名,本土化查询
selectenameas"姓名",round((sysdate-hiredate),0)as"工作年限"fromemporderby"工作年限"desc;
注:as是列别名的关键字,可以用英文双引号""里面的内容来表示该列的别名
12、对查询出来的员工薪水进行文字说明
selectename||''员工本月工资为:¥''||(sal+1500)as"公司员工本月工资表"fromemporderbysal;
注:||是Oracle的连接符,可以把查询出来的数据和其他字符串连接起来,''''单引号里面是字符串,可以把里面的字符串输入
13、过滤重复的数据
selectdistinctdeptnofromemp;
14、按照薪水排序查询工资少于2000
selectename,salfromempwheresal<=2000orderbysal;
15、查询薪水在某个区间的员工
selectename,salfromempwheresalbetween1500and2500orderbysal;
或者selectename,salfromempwheresal>=1500andsal<=2000orderbysal;
16、查询没有奖金或工资少于1500的员工
selectempno,ename,job,sal,commfromempwherecommisnullorsal<=1500;
注:null在Oracle数据库中是一个特殊的值,它既不表示0,也不表示空,是一个不能确定的未知数
selectempno,ename,job,sal,comm,sal+nvl(comm,0)fromempwherecommisnullorsal<=1500orderbysal+nvl(comm,0);
注:nvl(X,Y)是数据库的一个内部函数,表示如果X有值,则返回X的值,如果X为null,则返回Y的值
17、查看姓名中“M”开头的员工
selectename,job,salfromempwhereenamelike''M%'';
注:like是where中的模糊查询,后面字符串需要用单双引号括起来,M%表示以M开头的所有字符
18、where中的in关键字
selectename,job,fromempwherejobin(''SALESMAN'',''ANALYST'',''MANAGER'');
注:in表示在某个列中的多个值均符合,或者使用or代替,如:
selectename,jobfromempwherejob=''SALESMAN''orjob=''ANALYST''orjob=''MANAGER'';
19、统计公司每个岗位有多少个员工
selectjob,count()fromempgroupbyjob;
注:groupby:是Oracle数据库中的分组函数,可以这样理解,按照工作职位进行分组,然后统计每个职位的人数
count():是统计数量的一个函数,这里是统计公司每个岗位的人数
selectjobas"岗位",count()as"总人数"fromempgroupbyjoborderbycount();
20、统计总共要支付员工的薪水
selectsum(sal)+sum(nvl(comm,0))fromemp;
注:sum是Oracle数据库内部的一个函数,即所有数值之和
21、求员工的平均工资
selectround(avg(sal),2)fromemp;
注:avg数据库的求平均值函数
22、统计公司所有员工中最高、最低工资及相差多少
selectmax(sal),min(sal),max(sal)-min(sal)fromemp;
注:max统计最大的数值,min统计最小的数值
23、查找哪些岗位的平均工资高于2500
selectjob,avg(sal)fromemphavingavg(sal)>2500groupbyjob;
注:在使用groupby分组时,如有条件限制需要使用having,而不能使用where
having是筛选组,where筛选记录 |
|