0

I'm trying to write a SQL query in MS ACCESS and I've narrowed it down to the table below, but can't seem to get the last thing right without making several extremely large querys.

Here's the strucuture of thetable I'm trying to query:

enter image description here

The results I want: MemberId and year where memberId had most visits in that year.(That is which memberId had most visits 2014, which had most visits 2015 etc..and I also want the relevant year to be shown in the result)

Thanks!

Marcus Adams
  • 53,009
  • 9
  • 91
  • 143
user3284549
  • 313
  • 3
  • 9
  • Cn you show us your try,no matter how wrong? – Mihai Jan 12 '15 at 18:40
  • this group by should work . select memberId, Year, max(totalVisits) from myTable group by memberId, Year – radar Jan 12 '15 at 18:47
  • What about ties? E.g. MemberID 5 and 7 for 2014. – Marcus Adams Jan 12 '15 at 18:49
  • My Query only manages to get the max value for one year, so it's kinda useless. I tried your query now radar, problem is it returns several entries per year, I want only the one with highest visits for every year – user3284549 Jan 12 '15 at 18:53
  • Managed to solve it with help of another question link: http://stackoverflow.com/questions/612231/how-can-i-select-rows-with-maxcolumn-value-distinct-by-another-column-in-sql?rq=1 – user3284549 Jan 12 '15 at 19:04

1 Answers1

0

Sounds like you need to determine MAX(Visits) by year in a subquery, then JOIN to that:

SELECT a.*,b.Max_Visits
FROM YourTable a
JOIN (SELECT Year,MAX(Visits) AS Max_Visits
      FROM YourTable
      GROUP BY Year
     ) b
 ON a.Year = b.Year
 AND a.Visits = b.Max_Visits

If you want to see all members and not just those that had the most visits per year, you can change from JOIN to LEFT JOIN

If there's a tie, this returns both members.

Hart CO
  • 34,064
  • 6
  • 48
  • 63