简体   繁体   中英

How to query MAX(SUM(relation)) in Postgresql?

I have read several related threads on StackOverflow but none of them solves my problem. I have a Sales database as where I need to query for the customer who spent the most amount in buying stuff. For that, I need to find who bought which product using

SELECT  sum(qty*rate) 
AS exp from salesdetails as s JOIN sales as ss on (ss.invno = s.invno) 
JOIN customer as c ON (ss.customerno = c.custno) GROUP BY(c.name) 
ORDER BY sum(qty*rate);

It returns a table with the name of the person and what he spent in ascending order as

Output of command above:

在此处输入图片说明

While what I actually need is to only print a tuple when sum(qty*rate) is maximum. Currently I'm getting the results by sub querying like:

SELECT name, sum(qty*rate) FROM salesdetails as s JOIN sales as ss on (ss.invno=s.invno) 
JOIN customer as c ON (ss.customerno = c.custno) GROUP BY(c.name) 
HAVING sum(qty*rate) IN (SELECT max(exp) FROM (SELECT  sum(qty*rate) 
AS exp from salesdetails as s JOIN sales as ss on (ss.invno = s.invno) 
JOIN customer as c ON (ss.customerno = c.custno) GROUP BY(c.name) ORDER BY sum(qty*rate)) aa);

Expected Output:

在此处输入图片说明

Is there any shorter way to get to the output?

You want row_number() or distinct on :

SELECT DISTINCT ON (c.name) c.name, sum(qty*rate) AS exp
FROM salesdetails s JOIN
     sales ss
     on (ss.invno = s.invno) JOIN
     customer c
     ON (ss.customerno = c.custno)
GROUP BY c.name
ORDER BY c.name, sum(qty*rate) DESC;

Are you looking for something like this:

select * 
from (
       SELECT c.Name, sum(qty*rate) 
       AS exp from salesdetails as s JOIN sales as ss on (ss.invno = s.invno) 
       JOIN customer as c ON (ss.customerno = c.custno) 
       GROUP BY(c.name) 
       ORDER BY sum(qty*rate) desc
     ) t
limit 1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM