Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Query to only bring back Maximum of a Count field

Status
Not open for further replies.

psharma1

Programmer
Nov 16, 2009
10
0
0
US
I have a SQL statement (below) for SQL Server 2008 DB that returns a Division, a Dept Code, and a count of employees grouped by the Division & Dept Code.
All I want to display is the MAX count, so a sample of my SQL is:

Divison Dept_Code Count_Emp
1011 100 1
1011 101 122
1011 123 1
1011 198 1
1011 199 1
1012 100 3
1012 101 36
1012 123 2
1012 198 1


But all I want to display is:

Division Dept Count_Emp
1011 101 122
1012 101 36


select di.divId Division, Dpt.Dept_Code, count(Emp.Emp_id)
from division di, Department Dpt, Employee Emp
where Emp.DIVID = di.DIVID and
Emp.Dept_Code = Dpt.Dept_Code and
EMP.status = 'A'
group by di.divId, Dpt.Dept_Code
order by 1,2

How can this be acheived? I've applied all of my SQL skills but can't figure this out. Will this need multiple nested queries or a Having Clause would work?

Please help.

Thanks!
 
Hi Markros,

I'm having problem with paranthesis if I try to include the original query in place of "Results" in your response above.

Do I have to create a Temp table first and then use it in your query or is it possible to do it all together in 1 query.

Please elaborate and thanks for your response!

PS
 
Thanks Markros, this worked! This is going to be very useful for me.

Appreciate your help!
PS
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top