【问题标题】:Oracle display customer who purchased most cars购买汽车最多的甲骨文展示客户
【发布时间】:2015-05-18 11:42:52
【问题描述】:

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

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

我正在使用的表:

客户

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

销售交易

(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

请告诉我我做错了什么。

【问题讨论】:

标签: sql oracle group-by


【解决方案1】:

最简单的方法是使用 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;

【讨论】:

    【解决方案2】:

    这应该可行:

    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
    

    【讨论】:

    • 这是完美的伴侣,但是因为我只需要显示名称,而不是计数,我可以从查询中排除什么?
    • 您可以排除customer.name之后的count(*),如果您也想删除count,我会编辑答案
    【解决方案3】:
    select * from (
    select customer.name, count(*)
    from customer, salestransaction
    where customer.custid = salestransaction.custid
    group by (salestransaction.custid)
    order by count(*) desc
    ) where rownum=1
    

    【讨论】:

      【解决方案4】:

      使用连接而不是在 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);
      

      【讨论】:

      • 尽管如此,这段代码并不会只输出一个包含最多购买汽车的名称。它将输出所有客户名称的列表,并计算购买了多少辆汽车。另外,我尝试了几个使用连接的查询,而不是在 where 子句中加入它们,但我仍然没有得到我需要的答案。
      猜你喜欢
      • 1970-01-01
      • 2013-10-12
      • 1970-01-01
      • 2022-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-16
      • 1970-01-01
      相关资源
      最近更新 更多