Solved

Help with TSQL Aggregate query using TOP

Posted on 2003-11-28
2
334 Views
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).
0
Comment
Question by:deem1
2 Comments
 
LVL 6

Expert Comment

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

Accepted Solution

by:
RichardCorrie earned 125 total points
ID: 9837760

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

Richard
0

Featured Post

Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

Question has a verified solution.

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

When you hear the word proxy, you may become apprehensive. This article will help you to understand Proxy and when it is useful. Let's talk Proxy for SQL Server. (Not in terms of Internet access.) Typically, you'll run into this type of problem w…
This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.

792 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