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

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Query not returning correct field

Author  Topic 

105ben
Starting Member

16 Posts

Posted - 2012-12-29 : 16:13:01
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

11 Posts

Posted - 2012-12-30 : 05:28:45
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
   

- Advertisement -