Click here to Skip to main content
15,909,325 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
I have a table that looks like this :


Region   Country   Earnings

Americas    Canada   10000

Americas    Mexico    20000

Americas    USA     50000

Asia-Pac   China    70000

Asia-Pac   Japan    40000

  

I need a report that groups the results based on the Region and then the Country as well as orders by the Earnings within the Region in a descending manner. I am using the below query : 


Select Region, Country, SUM(Earnings) from MyTable

Group By Region, Country

Order By SUM(Earnings) DESC


However, the result set that I get looks like the below :


Region   Country   Earnings

Asia-Pac   China    70000

Americas    USA    50000

Asia-Pac   Japan    40000

Americas    Mexico    20000

Americas    Canada   10000


i.e. I get the result set ordered by Earnings in a descending manner but the grouping gets disturbed.

Any ideas?


What I have tried:

I have tried writing the query myself & its as below :

Select Region, Country, SUM(Earnings) from MyTable

Group By Region, Country

Order By SUM(Earnings) DESC
Posted
Updated 22-Aug-16 0:14am
Comments
[no name] 22-Aug-16 5:56am    
Your query does exactly what it should. You Group By Region _and_ Country and the table you Show does _only_ have entries of different Groups at the Moment.... add e.g another row for "Americas, Canada" with earning of 70'000 and you see everything is correct.
phil.o 22-Aug-16 6:02am    
Since you have only one country occurrence for each region, the result you get is correct. You may try to add some more region/country duplicates with different earnings to have a more meaningful result.
[no name] 22-Aug-16 6:11am    
I think you mean "for each Region" :)
phil.o 22-Aug-16 6:14am    
Oops :)
Now corrected. Thanks for pointing it.

Quote:
i.e. I get the result set ordered by Earnings in a descending manner but the grouping gets disturbed.
Any ideas?
Sure, it is what you asked for !

See the usage of "GROUP BY" and "ORDER BY"
SQL ORDER BY Keyword[^]
 
Share this answer
 
Try:
SQL
... ORDER BY Region ASC, SUM(Earnings) DESC
 
Share this answer
 
Comments
aakar 23-Aug-16 4:14am    
Thanks all for your suggestions! However, the report that I need should look like :

Region Country Earnings

Americas USA 50000

Americas Mexico 20000

Americas Canada 10000

Asia-Pac China 70000

Asia-Pac Japan 40000
OriginalGriff 23-Aug-16 4:22am    
And that's what the two ORDER BY clauses do...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900