简体   繁体   中英

Multiple rows with the same Max value - SQL

I have two tables, Customer and Orders .

  • Customer : Id, Name, Email
  • Orders : Id, OrderDate, Department, Total, Customer_Id

I built a query to get the customer with the highest total in each department:

select 
    Id, Name, dep, max(total_s) totals
from
    (select 
         c.Id, c.Name, o.Department dep, sum(o.Total) total_s
     from 
         Customer c
     join 
         Orders o on c.Id = o.CustomerId
     group by 
         1) sub
group by 3

This query returns the customer with the max sum of Total in each department, the problem is that I have one department with two customers (rows) that they have the same Max Total, but the query returns only one row. So how to return all the rows that they contains the Max value?

You can use rank() :

select c.Id, c.Name, o.Department, total,
from (select c.Id, c.Name, o.Department, sum(o.Total) as total,
             rank() over (partition by o.Department order by sum(o.Total) desc) as seqnum
      from Customer c join
           Orders o
           on c.Id = o.CustomerId
      group by c.Id, c.Name, o.Department
     ) sub
where seqnum = 1;

To be honest, I'm not sure how your query does anything useful. In almost any database, it would return an error because both the inner query and outer query have select columns that are not group by keys. In addition, the query never calculates the total for a customer within a single department.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM