Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: SQL Server
Expertise: Beginner
Oct 2, 1998

Selecting a maximum sum from a group

Question:
I need to write a query that selects the maximus sum for a group from a list like the one below.

Type      Value
A         100
B         200
C         300
A         300
B         100
C         342
The result should be C, 642. I tried "group by," but I could only get the sums.

Answer:
You must use what is essentially a two-step process.

1. Use a select type,sum(value) group by type to create a summary table.
2. Obtain the row with the max value from the summary result set.

It is possible to combine these two steps into one statement using derived tables. However, internally, it is still two steps. I've used a view to illustrate one way of implementing the steps.


create table test
(
	type char,
	num int
)
go

insert into test values('a',100)
insert into test values('b',100)
insert into test values('c',100)
insert into test values('a',100)
insert into test values('b',100)
insert into test values('c',200)
go


create view vwTest as
select type,  sum(num) as "total"
from test
group by type
go


select  type,total
from vwTest
where
total = (select max(total) from vwTest)


DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date