如何从sqlite查询中获取顶级组?

如何从sqlite查询中获取顶级组?,sql,sqlite,aggregate-functions,Sql,Sqlite,Aggregate Functions,我正在使用sqlite chinook数据库,遇到了以下情况: db表示一个音乐商店,其发票表格链接到客户 Invoices表中有一个total列,我可以使用sum()按客户表中的country分组对其进行聚合 SELECT c.country, sum(i.total) totalspent, c.firstname, c.lastname FROM invoices i left join customers c on c.custome

我正在使用sqlite chinook数据库,遇到了以下情况: db表示一个音乐商店,其
发票
表格链接到
客户

Invoices
表中有一个
total
列,我可以使用
sum()
客户
表中的
country
分组对其进行聚合

SELECT 
    c.country,
    sum(i.total) totalspent,
    c.firstname,
    c.lastname

FROM 
    invoices i
    left join customers c on c.customerid= i.customerid

group by
    c.country,
    c.firstname,
    c.lastname

order by 2 desc
这将输出如下内容:

.---------------------------------------------.
| Country  | totalspent | firstname | lastname |
|----------------------------------------------|
| Czech R. | 49.62      |  Helena   |  Holy    |
| USA      | 47.62      |  Richard  | Cunning  |
| Chile    | 46.62      |  Luis     | Rojas    |
| Hungary  | 45.62      |  Ladislav | Kovac    |
| Ireland  | 45.62      |  Hugh     | O'Reilly |
| USA      | 43.62      |  Julia    | Barnett  |
...
...
您会注意到,该表是按
totalspend
降序排列的。这将导致来自同一个国家的人因消费的多少而出现不同的顺序

我如何才能在每个国家只获得前1行? 我试图按每个国家分组,从
total
中选择max()
,但没有成功

以下是我的尝试:

select 
  ...
  ...
where
    sum(i.total) in (select max(sm) 
                     from ( select 
                                  sum(ii.total) sm 
                             from 
                                  invoices ii left join customers cc 
                                     on cc.customerid = ii.customerid 
                             where cc.country = c.country ))


 ...
 group by
    ...
但这也不起作用


必须有更直接的方法从结果行中只选择排名靠前的国家。

SQLite没有窗口功能

这只是一种方法,请检查它是否适合您的场景:

假设这是您当前的结果:

sqlite> create table c ( i int, p varchar(100), c varchar(100));
sqlite> insert into c values
   ...> ( 100, 'pedro', 'USA'),
   ...> ( 120, 'marta', 'Spain'),
   ...> (  90, 'juan',  'USA' ),
   ...> ( 130, 'laura', 'Spain' );
然后,查询可以是:

sqlite> select c.*
   ...> from c inner join
   ...>  ( select c, max(i) as i from c group by c) m 
   ...> on c.c = m.c and c.i=m.i;
在子查询中,我们得到每个国家的最大值

结果:

100|pedro|USA
130|laura|Spain
注意在您的情况下,您应该从选择中进行选择。

您可以使用CTE:

with ic as (
      select c.country, sum(i.total) as totalspent, c.firstname, c.lastname
      from invoices i left join
           customers c
           on c.customerid = i.customerid
      group by c.country, c.firstname, c.lastname
     )
select ic.*
from ic
where ic.totalspent = (select max(ic2.totalspent) from ic ic2 where ic2.country = ic.country);
order by 2 desc

这正是获得所需输出所需的,同时保持查询易于准备且高效。