常用易忘sql

常用易忘sql


ORACLE默认是根据ROWID来排序的啊,ROWID是数据库唯一标识不能更改的,
所以你想在数据库更改顺序是不可能。只能通过索引对字段排序,之后使用索引,
这样效果其实一样的。

关于表空间:
1 查看表空间:
  select *from v$tablespace;

2 创建临时表空间
  create temporay tablespace temp1 tempfile
  '/home/oracle/app/oradata/orcl/temp1.dbf' size 20M;

3 创建数据表空间
  create tablespace data datafile '/home/oracle/app/oradata/orcl/data.dbf'
  size 20M;

4 创建oudo表空间
  create undo tablespace undo_dud datafile '/home/oracle/app/oradata/oral/undo_dud.dbf'
  size 20M;

5 更改undo表空间属性
  alter system set undo_talespace=undo;



关于表属性:
1 表的后面增加一个属性
  alter table emp add (ename varchar2(10) not null);

2 在固定属性后面添加一个属性
  alter table emp add (job varchar2(9) not null) afer ename; (不行)

3 查看表在哪个表空间下
  select table_name, tablespace_name from user_tables where table_name='EMP';
  (这里EMP一定要大写)

4 更改列属性
   alter table emp modify job varchar2(5);


5 查看表的属性
  desc emp;
6 清空表
truncate table ‘emp’;

6 查看表的行数
  select count(column_id) from user_tab_columns where tabel_name = 'emp';


7 修改关系表的名字
  alter table emp rename to ddemp;

8 修改表属性名字
  alter table emp rename column empno to id;

9 删除行属性
  alter table emp drop column empno;



查询语句:

1  找出有奖金的员工的不同工作
  select distinct job from emp where comm is not null and comm>0;

2 找出部门10中既不是经理也不是普通员工,而且工资大于2000的员工
  select *from emp where deptno=10 and job not in ('manager', 'clerk') and sal>2000;

3  显示雇员名字,根据其服务年限,将最老的雇员排在最前面
   select ename from emp order by hiredate;

4  查找工资与奖金的总共total
   select sal, comm, nvl2(comm, sal+comm, sal) total from emp;
5  查找在相同deptno的人的平均工资的最高
   select max(avg(sal)) from emp group by deptno;

6  算出部门30中得到最多奖金的员工的姓名
   select ename from emp where comm = (select max(comm) from emp where deptno=30);

7  算出每个职位员工数的和最低工资
   select job,min(sal), count(*) from emp group by deptno;

8  
   select deptno, job, avg(sal)
   from emp
   where hiredate>=to_date('1981-05-01', 'yyyy-mm-dd')
   group by deptno, job
   having avg(sal)>1200
  order by deptno, job;

9  统计各个部门下平均工资大于500的部门
   select deptno, avg(sal) from emp group by deptno having avg(sal)>500;

10 将第一个字母变成大写
   select initcap('hello world') from dual;

SQL 中的 TRIM 函数是用来移除掉一个字串中的字头或字尾。最常见的用途是移除字首或字尾的空白。这个函数在不同的资料库中有不同的名称:
MySQL: TRIM(),RTRIM(),LTRIM()
Oracle: RTRIM(),LTRIM()
SQL Server: RTRIM(),LTRIM()



11 算出每个职位的员工数和最低工资
   select job, min(sal), count(*) from emp group by job;

12 得到工资大于自己部门平均工资的员工的信息
   select *from emp e1, (select depno, avg(sal)  as avgsal from emp group by deptno)e2
   where e1.deptno=e2.deptno and e1.sal>e2.avgsal;

13 分组统计每个部门下,每种职位的平均奖金 (也要算没得奖金的人) 和总工资 (包括奖金)
   select deptno, job, avg(nvl(comm, 0)), sum(sal+nvl(comm, 0)) from emp group deptno, job;

14算出每个部门,每个职位的平均工资和平均奖金, 如果平均奖金大于300,显示。。
   按部门编号降序,平均工资降序排列
   SELECT EMPNO, ENAME, SAL,
    CASE DEPTNO
    WHEN 10 THEN '10'
    WHEN 20 THEN '20'
    WHEN 30 THEN '30'
    ELSE 'ELSE'
    END DEPTNO
    FROM EMP;


请使用浏览器的分享功能分享到微信等