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

问题描述 投票:1回答:2

我正在使用sqlite chinook数据库,并遇到了这种情况:db代表一个音乐商店,其中invoices表链接到customers

Invoices表有一个total列,我可以使用来自sum()表的countrycustomers分组来汇总它。

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  |
...
...

您会注意到该表按totalSpent降序排序。这将导致来自同一国家的人们由于他们花了多少而以不同的顺序出现。

我怎样才能获得每个国家的前1行?我试图按每个国家分组的select max() total,但是没有用。

这是我尝试的:

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
    ...

但那也行不通。

必须有更直接的方法从结果行中仅选择顶部国家/地区。

sql sqlite aggregate-functions
2个回答
1
投票

您可以使用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

0
投票

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

请注意,在您的情况下,您应该从您的选择中进行选择。

© www.soinside.com 2019 - 2024. All rights reserved.