1

I'm currently trying to answer the following question:

Display the name of the customer who has purchased the most cars from Archie’s Luxury Motors.

Tables I'm working with:

Customer

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

SalesTransaction

(VIN, custID, agentID, dateOfSale, agreedPrice)

My query

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;

Now I've found out that I cannot use analytic functions (rownum & rank)

How would I go about doing this with using pure transactional SQL only?

Rodi Marcus
  • 107
  • 1
  • 1
  • 9
  • What are *"analytic functions"*? – Phil May 21 '15 at 04:57
  • `rownum` isn't a function. Given that Oracle has no `LIMIT` or `TOP` clauses, I don't see another way – Phil May 21 '15 at 04:59
  • You could use MAX and COUNT – President Camacho May 21 '15 at 05:00
  • Seems I spoke too soon ~ http://stackoverflow.com/questions/470542/how-do-i-limit-the-number-of-rows-returned-by-an-oracle-query-after-ordering/26051830#26051830 – Phil May 21 '15 at 05:01
  • rownum is indeed a function. source: http://docs.oracle.com/cd/E11882_01/server.112/e41084/functions156.htm#SQLRF06100 – Rodi Marcus May 21 '15 at 05:03
  • 1
    `ROW_NUMBER()` is a function. `ROWNUM` is a pseudo-column, These are different things. – APC May 21 '15 at 05:17
  • "*I cannot use analytic functions*" - why? "*in pure transactional SQL only*" - window functions **are** "pure" SQL (they have been part of the SQL standard for over 10 years now) –  May 21 '15 at 08:32

1 Answers1

0

You could use MAX and COUNT aggregate functions:

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
  );

An example from EMP and DEPT table:

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>
Lalit Kumar B
  • 47,486
  • 13
  • 97
  • 124