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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using Max(Count(*)) query

Status
Not open for further replies.

gj0519

MIS
May 8, 2003
69
US
I have a query I wrote in Oracle but I can not seem to get it to work in MS SQL 2005.
I need to get the name of the author with the most orders.
The query below gives me the name and the max count, but I only want to see the name. That is where I am hung up.
Code:
(Select  fname, Max(TotalB) as Total2
		From 
			Select a2.fname, count(*) as TotalB
				from author a2 join bookauthor ba
				on a2.authorid = ba.authorid join books b
				on ba.isbn = b.isbn join orderitems oi
				on b.isbn = oi.isbn
				Group by a2.fname)Tbl
				Group By fname)

Thanks,
GJ
 
Code:
Select  fname, Max(TotalB) as Total2
        From
            (
            Select a2.fname, count(*) as TotalB
                from author a2 join bookauthor ba
                on a2.authorid = ba.authorid join books b
                on ba.isbn = b.isbn join orderitems oi
                on b.isbn = oi.isbn
                Group by a2.fname)Tbl
                Group By fname) As AliasName

-George

"The great things about standards is that there are so many to choose from." - Fortune Cookie Wisdom
 
Thanks for the reply, what I am after is the author with the highest total, I re-wrote the query.
Code:
Select count(oi.order#) as Total, a.fname, a.lname
from author a join bookauthor ba
on a.authorid = ba.authorid join books b
on ba.isbn = b.isbn join orderitems oi
on b.isbn = oi.isbn
Group By a.fname, a.lname

The results I get:
Code:
12	JACK	BAKER
7	JAMES	AUSTIN
6	JANICE	JONES
6	JUAN	ADAMS
1	LISA	PORTER
2	LISA	WHITE
5	OSCAR	FIELDS
8	ROBERT	ROBINSON
1	SAM	SMITH
6	TINA	PETERSON
2	WILLIAM	WHITE

Thanks,
GJ
 
Hi!

Code:
Select [red]TOP 1[/red] count(oi.order#) as Total, a.fname, a.lname
from author a join bookauthor ba
on a.authorid = ba.authorid join books b
on ba.isbn = b.isbn join orderitems oi
on b.isbn = oi.isbn
Group By a.fname, a.lname
[red]ORDER BY 1 DESC[/red]

Regards
 
Code:
Select count(oi.order#) as Total, a.fname, a.lname
from author a join bookauthor ba
on a.authorid = ba.authorid join books b
on ba.isbn = b.isbn join orderitems oi
on b.isbn = oi.isbn
Group By a.fname, a.lname
having count(oi.order#) = max(count(oi.order#))

This will get ties as well (items sharing the highest order count)

And if your order# can be null it won't be included in the count...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top