How to use MAX() on a subquery result?

后端 未结 7 1846
名媛妹妹
名媛妹妹 2021-02-07 08:48

I am new to Oracle and the SQL world. I have a slight issue with a query that I cannot figure out for the life of me, I have spent a few hours trying different approaches and I

相关标签:
7条回答
  • 2021-02-07 09:41

    You cannot use a derived table directly in where clause it will give table or view does not exist error so to get the max count value you can use HAVING clause or Analytical Functions or Rownum like

    select * from
          (Select membership.mem_desc,membership.mem_max_rentals,membership_history.mem_type,      
          count(membership_history.MEM_TYPE) as membership_count
          from membership_history a
          JOIN membership b ON b.mem_type = a.mem_type
          group by (membership_history.mem_type,membership.mem_desc,membership.mem_max_rentals)
          having count(a.MEM_TYPE) = (Select      
          MAX(count(a.MEM_TYPE)) from membership_history a
          JOIN membership b ON b.mem_type = a.mem_type
          group by (a.mem_type,b.mem_desc,b.mem_max_rentals)));
    

    (OR)

    select * from
    (SELECT g.*,rank() over (order by membership_count desc) rnk from
          (Select membership.mem_desc,membership.mem_max_rentals,membership_history.mem_type,      
          count(membership_history.MEM_TYPE) as membership_count
          from membership_history
          JOIN membership ON membership.mem_type = membership_history.mem_type
          group by (membership_history.mem_type,membership.mem_desc,membership.mem_max_rentals)) g)
    WHERE rnk=1;
    

    (OR)

    select * from
    (SELECT g.*,rownum rn from
          (Select membership.mem_desc,membership.mem_max_rentals,membership_history.mem_type,      
          count(membership_history.MEM_TYPE) as membership_count
          from membership_history
          JOIN membership ON membership.mem_type = membership_history.mem_type
          group by (membership_history.mem_type,membership.mem_desc,membership.mem_max_rentals)
          order by membership_count desc) g)
    WHERE rn=1;
    
    0 讨论(0)
提交回复
热议问题