列出每个部门的前十名员工

时间:2013-05-26 02:01:39

标签: sql greatest-n-per-group

如何按顺序列出每个部门的前十名员工,并根据购买总额订购员工的每个部门?

这些是表格:

CREATE TABLE EMP (
    EMPNO NUMBER(4),
    ENAME VARCHAR2(20),
    POSITION VARCHAR2(20),
    DEPTNO NUMBER(2)
);

CREATE TABLE DEPT (
    DEPTNO NUMBER(2),
    DNAME VARCHAR2(20)
);

CREATE TABLE CLIENT (
    CLIENTNO NUMBER(5),
    CNAME VARCHAR2(20),
    PHONE VARCHAR2(10)
);

CREATE TABLE PURCHASE (
    PURCHASENO  NUMBER(5),
    RECEIPTNO   NUMBER(6),
    SERVICETYPE VARCHAR2(25),
    PAYMENTTYPE VARCHAR2(10),
    GST     VARCHAR2(3),
    AMOUNT      NUMBER(4),
    SERVEDBY    NUMBER(4),
    CLIENTNO    NUMBER(5)
);

尝试编辑:

SELECT DISTINCT *
FROM (SELECT E.ENAME, D.DEPTNO, COUNT(P.PURCHASENO) AS TOTALAMOUNT,
             AVG(P.AMOUNT)AS AVGAMOUNT, MAX(P.AMOUNT)AS HIGHESTAMOUNT,
             SUM(P.AMOUNT)AS TOTALAMOUNTPURCHASE,
             DENSE_RANK() OVER(PARTITION BY DEPTNO ORDER BY AMOUNT DESC)RANK
      FROM EMP E, DEPT D, PURCHASE P
     )
WHERE RANK<=10

1 个答案:

答案 0 :(得分:0)

以下是解决问题的方法之一:

 select *
 from (select s.deptno, empno,
              row_number() over (partition by s.deptno order by totamount desc) as seqnum
       from (select servedby, sum(amount) as totamount
             from purchase p
             group by servedby
            ) ps join
            emp e
            on ps.servedby = e.empno
       group by deptno, empno
      ) t
 where seqnum <= 10;

您的原始查询缺少表和中间聚合级别之间的连接。