Help with TSQL Aggregate query using TOP

Posted on 2003-11-28
Last Modified: 2006-11-17
I have two tables, Person (id int, name varchar()) and Appointment(date datetime, personid int, notes varchar())
personid from the Appointment table reference is from the Person table.

The Person table contains is and name of some people. The Appoinment table contains the date the each person was visited. There can be many entries in the Appoinment table for each person. i.e. They is a record of many visits for each person.

I need a query that gives the 5 most recent visits for ALL the people in the Person table, not just one person. So I need a query that for each person in the person table will return the 5 (or however many) most recent vists. i.e.(date <= today).
Question by:deem1
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions

Expert Comment

ID: 9837724
Can you post same sample with data and what do you want as ansewer ?
LVL 10

Accepted Solution

RichardCorrie earned 125 total points
ID: 9837760

for convenience add an Identity field to Appoint ment table (AppointmentID) then
 Person P
inner join
Appointment A
P.PersonID = A.PersonID
A.Appointmentid in(Select TOP 5 AppointmentID from Appointment AP Where AP.PersonID = A.PersonID and AP.Date<=getdate() order by AP.Date DESC)


Featured Post

Free eBook: Backup on AWS

Everything you need to know about backup and disaster recovery with AWS, for FREE!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
In the first part of this tutorial we will cover the prerequisites for installing SQL Server vNext on Linux.
This video shows, step by step, how to configure Oracle Heterogeneous Services via the Generic Gateway Agent in order to make a connection from an Oracle session and access a remote SQL Server database table.
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…

732 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question