oracle显示购买大多数没有分析功能的汽车的客户

时间:2015-05-21 04:55:24

标签: sql oracle

我目前正在尝试回答以下问题:

显示从Archie的Luxury Motors购买最多汽车的客户的名字。

我正在使用的表:

客户

(custID, name, DOB, streetAddress, suburb, postcode,
gender, phoneNo, email, type)

SalesTransaction

(VIN, custID, agentID, dateOfSale, agreedPrice)

我的查询

select * 
from (
select customer.name
from customer, salestransaction
where customer.custID = salestransaction.custID
group by (customer.name), salestransaction.custID
order by count(*) desc
)
where rownum=1;

现在我发现我不能使用分析函数(rownum& rank)

如何仅使用纯事务SQL来执行此操作?

1 个答案:

答案 0 :(得分:0)

您可以使用 MAX COUNT 汇总功能:

WITH data AS
  (SELECT c.name cust_nm,
    COUNT(*) cnt
  FROM customer c,
    salestransaction s
  WHERE c.custID = s.custID
  GROUP BY c.NAME
  ORDER BY cnt DESC
  )
SELECT cust_nm FROM data WHERE cnt =
  (SELECT MAX(cnt) FROM DATA
  );

来自EMP和DEPT表的示例:

SQL> WITH data AS
  2    (SELECT e.deptno,
  3      COUNT(*) cnt
  4    FROM emp e,
  5      dept d
  6    WHERE e.deptno = d.deptno
  7    GROUP BY e.deptno
  8    ORDER BY cnt DESC
  9    )
 10  SELECT deptno FROM DATA WHERE cnt =
 11    (SELECT MAX(cnt) FROM DATA
 12    );

    DEPTNO
----------
        30

SQL>