如何从 PostgreSQL 数据集中的某一列获取所有最大值

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

我被要求找出不同国家/地区的顶级用户,但是,其中一个国家/地区有 2 个用户的消费金额相同,因此他们应该都是顶级用户,但我无法获得最大值在这个国家有 2 个值。 这是代码:

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在Invoice里面,里面有所有国家的名字。

TOTAL也在invoice里面,显示客户每次购买花费了多少(所以每次购买都有不同的费用和税金,total显示用户每次支付的最终价格)

客户有 ID、姓名、姓氏,我从其 ID 中提取了他每次购买的总额

MAX 是在找到每个客户的总和后使用的,它是按国家/地区分组的,这样我就可以找到每个国家/地区的最大值,但是我似乎找不到最后一个国家/地区的最大值,最大值为 2值

使用rank()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;

子查询查找每个国家/地区每个客户的金额——重要的是计算具有相同排名的关系组合的排名。外部查询只是引入了您似乎需要的额外客户信息。

这是它对我有用的方法,因为我被限制使用许多命令,例如 RIGHT JOINRANK()(正如 Gordon Linoff 所建议的那样)所以我不得不为 anamoly 创建第三个案例并使用 union 加入它。此解决方案仅适用于这种情况,好的解决方案是 Gordon Linoff 发布的解决方案:

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
) ,
t3 AS (
SELECT DISTINCT c.customerid as CustomerId  ,c.firstname as FirstName,c.lastname as LastName, i.billingcountry as Country,t1.tot as TotalSpent  
FROM t1
JOIN customer c
ON c.customerid = t1.customerid
JOIN invoice i ON i.customerid = c.customerid
WHERE i.billingcountry = 'United Kingdom'
ORDER BY t1.tot DESC
LIMIT 2
)
SELECT *
FROM t2
UNION 
SELECT * FROM t3
ORDER BY t2.country