SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

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

105ben
Starting Member

United Kingdom
16 Posts

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

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?

shenulal
Starting Member

India
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  
 New 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.02 seconds. Powered By: Snitz Forums 2000