Please start any new threads on our new site at We've got lots of great SQL Server experts to answer whatever question you can come up with.

Our new SQL Server Forums are live! Come on over! We've restricted the ability to create new threads on these forums.

SQL Server Forums
Profile | Active Topics | Members | Search | Forum FAQ
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Query not returning correct field
 Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Starting Member

United Kingdom
16 Posts

Posted - 12/29/2012 :  16:13:01  Show Profile  Reply with Quote

the following query will find the total number of occurrences of every person_id in the attendance table, and list the figure and each person_id. Then when the second select runs to return the maximum and the person_id that has that maximum, its returning the maximum figure ok but then the person_id is just the first one in the count_temp table, regardless of which one has the highest total

select max(count), person_id
from (select person_id, count(person_id) as count
from attendance as a
group by a.person_id) as count_temp

can anyone see why?

Starting Member

11 Posts

Posted - 12/30/2012 :  05:28:45  Show Profile  Reply with Quote
You cannot run the above query as it will have the aggregate function using along in the second select also.
re-write like this

select top 1 count,person_id
from (select person_id, count(person_id) as count
from #tmp as a
group by a.person_id)
as count_temp order by count desc

hope this will solve your issue..
Go to Top of Page
  Previous Topic Topic Next Topic  
 Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.03 seconds. Powered By: Snitz Forums 2000