找到最高的金额,尽管有不止一个达到相同的金额
Find the highest amount although there are more than one achieving the same amount
我想为每个国家找到最好的客户,尽管有一个国家有两个相同数量的客户,我希望他们都出现。
select customerid,firstname,lastname,country, max(total_amt)
from (select invoice.customerid, customer.firstname,lastname,
sum(invoice.total)total_amt,customer.country
from invoice
join customer
on customer.customerid= invoice.customerid
group by invoice.customerid,customer.country)t2
group by country;
使用window函数:
select c.*
from (select c.country, c.customerid, c.firstname c.lastname, sum(i.total) as total,
dense_rank() over (partition by c.country order by sum(i.total) desc) as seqnum
from customer c join
invoice i
on c.customerid = i.customerid
) c
where seqnum = 1;
请注意,我还引入了 window 函数,因此查询更易于编写和阅读。
我想为每个国家找到最好的客户,尽管有一个国家有两个相同数量的客户,我希望他们都出现。
select customerid,firstname,lastname,country, max(total_amt)
from (select invoice.customerid, customer.firstname,lastname,
sum(invoice.total)total_amt,customer.country
from invoice
join customer
on customer.customerid= invoice.customerid
group by invoice.customerid,customer.country)t2
group by country;
使用window函数:
select c.*
from (select c.country, c.customerid, c.firstname c.lastname, sum(i.total) as total,
dense_rank() over (partition by c.country order by sum(i.total) desc) as seqnum
from customer c join
invoice i
on c.customerid = i.customerid
) c
where seqnum = 1;
请注意,我还引入了 window 函数,因此查询更易于编写和阅读。