Search code examples
sqlpostgresqlsubquerymax

How can i get all the MAX values from a certain column in a dataset in PostgreSQL


I'm asked to find the top user for different countries, however, one of the countries has 2 users with the same amount spent so they should both be the top users, but I can't get the max value for 2 values in this country. Here is the code:

WITH t1 AS (
SELECT c.customerid,SUM(i.total) tot
FROM invoice i
JOIN customer c ON c.customerid = i.customerid
GROUP BY 1
ORDER BY 2 DESC
),
t2 AS (
SELECT c.customerid as CustomerId   ,c.firstname as FirstName,c.lastname as LastName, i.billingcountry as Country,MAX(t1.tot) as TotalSpent
FROM t1
JOIN customer c
ON c.customerid = t1.customerid
JOIN invoice i ON i.customerid = c.customerid
GROUP BY 4
ORDER BY 4
)
SELECT *
FROM t2

BILLINGCOUNTRY is in Invoice, and it has the name of all the countries.

TOTAL is also in invoice and it shows how much is spent for each purchase by Customer (so there are different fees and taxes for each purchase and total shows the final price payed by the user at each time)

Customer has id,name,last name and from its' ID I'm extracting the total of each of his purchases

MAX was used after finding the sum for each Customer and it was GROUPED BY country so that i could find the max for each country, however I can't seem to find the max of the last country that had 2 max values


Solution

  • Use rank() or dense_rank():

    SELECT c.*, i.tot
    FROM (SELECT i.customerid, i.billingCountry, SUM(i.total) as tot,
                 RANK() OVER (PARTITION BY i.billingCountry ORDER BY SUM(i.total) DESC) as seqnum
          FROM invoice i
          GROUP BY 1, 2
         ) i JOIN
         customer c
         ON c.customerid = i.customerid
    WHERE seqnum = 1;
    

    The subquery finds the amount per customer in each country -- and importantly calculates a ranking for the combination with ties having the same rank. The outer query just brings in the additional customer information that you seem to want.