group by with sum后的最大值

azpvetkf  于 2021-07-29  发布在  Java
关注(0)|答案(1)|浏览(476)

我试图从这两张表中得到客户和发票的信息:每个国家每年的发票总额!所以我写的是:

SELECT SUM(i.total) AS Total_invoice, strftime(‘%Y’, i.InvoiceDate) AS year, c.country
FROM invoice i JOIN
     customer c
     ON i.CustomerId = c.CustomerId
GROUP BY 2,3
ORDER BY 1 DESC;

所以我得到了每年的发票总额!如果我想要每个国家的最大值(总数),你怎么办?例如,我想为每个国家的最大(总数),年和国家!你能帮忙吗?非常感谢您在这里输入图像描述

7tofc5zh

7tofc5zh1#

例如,我想为每个国家的最大(总数),年和国家!
为此,请使用窗口函数:

SELECT yc.*
FROM (SELECT SUM(i.total) AS Total_invoice, strftime(‘%Y’, i.InvoiceDate) AS year, c.country,
             ROW_NUMBER() OVER (PARTITION BY c.country ORDER BY SUM(i.total) DESC) as seqnum
      FROM invoice i JOIN
           customer c
           ON i.CustomerId = c.CustomerId
      GROUP BY 2, 3
     ) yc
WHERE seqnum = 1
ORDER BY 1 DESC;

相关问题