【问题标题】:How return two equal max values for the same country when the query is grouped by the country?当查询按国家/地区分组时,如何为同一国家/地区返回两个相等的最大值?
【发布时间】:2019-08-13 23:21:34
【问题描述】:

例如,我必须编写一个查询来显示在每个国家/地区花费最多的客户,但是如果一个国家/地区有两个具有相同最大值的客户,我必须在输出中显示他们两个。

我编写了返回每个国家/地区每个客户的最大值的查询,但我的示例中的最后一个国家“英国”有两个具有相同最大值的客户,我无法同时显示他们。

SELECT c1.CustomerId, c1.FirstName,c1.LastName,c1.Country, 
       MAX(c1.TotalSpent) as TotalSpent
FROM
    (SELECT c.CustomerId,c.FirstName, c.LastName,i.BillingCountry 
            Country, SUM(i.Total) totalspent
     FROM Customer c
     JOIN Invoice i
     ON c.CustomerId = i.CustomerId
     GROUP BY 1
     ORDER BY totalspent
    ) c1
GROUP BY 4
ORDER BY Country

【问题讨论】:

    标签: sql sqlite


    【解决方案1】:

    使用窗口函数!:

    SELECT c.*
    FROM (SELECT c.CustomerId, c.FirstName, c.LastName, i.BillingCountry as Country,
                 SUM(i.Total) as totalspent,
                 DENSE_RANK() OVER (PARTITION BY i.BillingCountry ORDER BY SUM(i.Total) DESC) as seqnum
          FROM Customer c JOIN
               Invoice i
               ON c.CustomerId = i.CustomerId
          GROUP BY c.CustomerId, c.FirstName, c.LastName, i.BillingCountry
         ) c
    WHERE seqnum = 1
    ORDER BY Country;
    

    这也修复了您的 GROUP BY 子句,使它们与被选择的列保持一致。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-20
      相关资源
      最近更新 更多