3

Suppose I have a table with 3 columns:

  • YEAR
  • COMPANY
  • DEPARTMENT
  • SALES

And I wanted to display the following:

  • COMPANY
  • DEPARTMENT
  • SUM(SALES)

The additional requirement being that the COMPANY with the Maximum Sales (across all departments) shows first, and the rest of the results ordered accordingly.

How would I go about writing my query?

I've tried the following, and it doesn't work:

SELECT t1.company,
   cs1.deparment, 
   SUM(cs1.sales) 
FROM   company_sales cs1, 
   (SELECT cs2.company, 
                   SUM(cs2.sales) 
            FROM   company_sales cs2
            WHERE  cs2.company IS NOT NULL 
            GROUP  BY cs2.company 
            ORDER  BY 2 DESC) t1
WHERE  cs1.company = t1.company 
GROUP  BY t1.company,  
      cs1.deparment;
3
  • BTW, I'm trying this in PostgreSQL. Commented Dec 22, 2015 at 23:37
  • select company,department,sum(sales) from table group by company,department order by company Commented Dec 22, 2015 at 23:41
  • @ivan, there is more to the requirement than just grouping and ordering at one level. Please refer to my question again. Commented Dec 22, 2015 at 23:47

2 Answers 2

3

You can do this using window functions:

select company, department, sum(sales)
from t
group by company, department
order by sum(sum(sales)) over (partition by company) desc, company;

You can also include the expression in the select clause to see the sum of sales for the entire company.

Sign up to request clarification or add additional context in comments.

4 Comments

Worked like a Charm !! Thanks for the solution.
you require a second condition in that order by clause i.e. , department
@Used_By_Already . . . Actually, it does need a second condition -- company -- to handle ties. I'm not sure what subsequent keys should be.
the rest of the results ordered accordingly. is very unclear but suggests it needs both company (as tie breaker) and department after that. cheers.
0

Try:

 SELECT company,department,sum(sales) 
 FROM table GROUP BY company,department 
 ORDER BY Max(sales)

1 Comment

Anton, this won't work for me, as I'm looking at Sales of a Company across all departments, not just one department.

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.