我目前正在尝试回答以下问题:
显示从Archie的Luxury Motors购买最多汽车的客户的名字。
表I'我正在使用:
客户
(custID, name, DOB, streetAddress, suburb, postcode,
gender, phoneNo, email, type)
SalesTransaction
(VIN, custID, agentID, dateOfSale, agreedPrice)
我尝试了以下查询:
select customer.name
from customer, salestransaction
where customer.custid = salestransaction.custid
group by (salestransaction.custid)
having count(salestransaction.custid) = max(salestransaction.custid);
我收到以下错误:
ORA-00979: not a GROUP BY expression
请告诉我我做错了什么。
答案 0 :(得分:2)
最简单的方法是使用RANK:
select customer.name, st.cnt
from customer
join
(
select
custid,
count(*) as cnt,
rank() over (order by count(*) desc) as rnk
from salestransaction
group by custid
) st
on customer.custid = st.custid
where st.rnk = 1;
答案 1 :(得分:1)
http://www.exmaple.com/images/img1.png
答案 2 :(得分:1)
可能这应该有效:
select * from (
select customer.name
from customer, salestransaction
where customer.custID = salestransaction.custID
group by (salestransaction.custID), customer.name
order by count(*) desc
) where rownum=1
答案 3 :(得分:0)
使用连接而不是在where子句中加入它们,同时放入
SELECT c.name, MAX(s.custid) FROM (
SELECT c.name, Count(s.custid)
FROM customer c
INNER JOIN salestransaction s ON c.custid = s.custid
GROUP BY c.name);