简体   繁体   中英

Find row that has the largest sum

I have data for tutors. I recorded hours spent tutoring by month in the SESSION table. I need to know who had the most tutoring hours in March, 2006.

TABLE TUTOR

tutorID      
1
2

TABLE SESSION

tutorID     Hours      Month
1           2          March
1           1          March
2           1          March

Expected Output:

TutorID
1

I would suggest:

select top 1 sum(Hours), tutorID from SESSION where Month like 'March' group by 
tutorID order by sum(Hours) DESC

Use 2 CTE s.
The 1st will return all the sums for each tutor.
The 2nd will return the maximum of the sums returned by the 1st cte.
Finally your select statement will return only the tutors from the 1st cte that have sum of hours equal to that maximum returned by the 2nd cte.

with 
  sumcte as (
    select tutorID, sum(hours) sumhours 
    from session 
    where month = 'March' -- here there should be another condition for the year?
    group by tutorID 
  ),
  maxcte as (
    select max(sumhours) maxhours from sumcte
  )  
select tutorid from sumcte
where sumhours = (select maxhours from maxcte)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM