2

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:

enter image description here

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:

enter image description here

Is there any shorter way to get to the output?

2 Answers 2

1

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;
Sign up to request clarification or add additional context in comments.

8 Comments

It gave the following error: ERROR: syntax error at or near "1" LINE 1: select top 1 * ^
Edited the answer. Could u please try again? @AashutoshRathi
It gives ERROR: syntax error at or near ";" LINE 6: ORDER BY sum(qty*rate) desc; now. also, you have to add a semicolon at end.
Maybe now, removed the semi-colon after desc and added it to the end? @AashutoshRathi
The columns you want to see in your output, you can add them in the select clause of the subquery. Edited answer. @AashutoshRathi
|
1

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;

1 Comment

It gives the whole table, I just need the one who spent most.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.