单表统计
select count(*) from emp; select job,sum(sal),count(*) from emp group by job; select deptno,max(hiredate),min(hiredate) from emp group by deptno; select trunc(hiredate,'yyyy'),count(distinct deptno),count(*) from emp group by trunc(hiredate,'yyyy'); select deptno,listagg(ename,',')within group(order by empno) from emp group by deptno; select deptno,cast(listagg(ename,',')within group(order by empno) as varchar(50)) namelist from emp group by deptno;
多表关联统计
select * from salgrade; select emp.*,grade from emp,salgrade; select grade,sum(sal) from emp,salgrade group by grade; select emp.*,grade from emp,salgrade where sal between losal and hisal; select grade,sum(sal) from emp,salgrade where sal between losal and hisal group by grade; select deptno,count(*),count(empno) from emp right join dept using(deptno) group by deptno; select dept.deptno,count(*),count(empno) from emp right join dept on emp.deptno=dept.deptno group by dept.deptno; select e.deptno,grade,min(sal),max(sal) from emp e,salgrade s,dept d where sal between losal and hisal and e.deptno=d.deptno group by e.deptno,grade order by 1,2; select e.deptno,min(sal),max(sal) from emp e,salgrade s,dept d where sal between losal and hisal and e.deptno=d.deptno group by e.deptno order by 1; select e.deptno,min(sal),max(sal) from emp e,salgrade s,dept d where sal between losal and hisal and e.deptno=d.deptno group by e.deptno,grade order by 1,2;
固定行列转换
create table shigu( sjname varchar2(20), yuefeng varchar2(10), sgsl number); insert into shigu values('司机张','三月',1); insert into shigu values('司机刘','一月',2); insert into shigu values('司机刘','二月',1); commit; insert into shigu values('司机张','二月',2); select * from shigu; select sjname,Decode(yuefeng,'一月',sgsl,0) m1,Decode(yuefeng,'二月',sgsl,0) m2,Decode(yuefeng,'三月',sgsl,0) m3 from shigu; select sjname, max(m1), max(m2), max(m3) from (select sjname, Decode(yuefeng, '一月', sgsl, 0) m1, Decode(yuefeng, '二月', sgsl, 0) m2, Decode(yuefeng, '三月', sgsl, 0) m3 from shigu) group by sjname;
分组求和统计
select e.deptno,grade,count(*) from emp e,salgrade s where sal between losal and hisal group by rollup(e.deptno,grade) order by deptno,grade;
select e.deptno,grade,count(*) from emp e,salgrade s where sal between losal and hisal group by cube(e.deptno,grade) order by deptno,grade;
select e.deptno,grade,count(*) from emp e,salgrade s where sal between losal and hisal group by e.deptno,rollup(grade) order by deptno,grade;
下面这个链接总结的不错
http://blog.sina.com.cn/s/blog_7e04e0d00101g6jb.html
只按部门编号和只按薪水等级统计人数
select e.deptno,grade,count(*) from emp e,salgrade s where sal between losal and hisal group by grouping sets(e.deptno,grade) order by deptno,grade;