我正在使用sqlite chinook数据库,并遇到了这种情况:
db表示一个音乐商店,其中invoices
个表链接到customers
。
Invoices
表格有一个total
列,我可以使用sum()
来自country
表的customers
分组对其进行汇总。
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
...
但这也行不通。
必须有更直接的方法从结果行中仅选择最顶层的国家/地区。
答案 0 :(得分: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
答案 1 :(得分:0)
SQLite没有窗口函数。
这只是一种方法,请检查它是否适用于您的方案:
我们假设这是您当前的结果:
comments
然后,查询可能是:
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;
注意在您的情况下,您应该从您的选择中进行选择。