Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

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



Application Security Testing: An Integral Part of DevOps

Selecting a maximum sum from a group

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.

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

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)

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

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

DevX Pro
Comment and Contribute






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



We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.
Thanks for your registration, follow us on our social networks to keep up-to-date