?
Solved

Help with TSQL Aggregate query using TOP

Posted on 2003-11-28
2
Medium Priority
?
338 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
[X]
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
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 375 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

What Is Blockchain Technology?

Blockchain is a technology that underpins the success of Bitcoin and other digital currencies, but it has uses far beyond finance. Learn how blockchain works and why it is proving disruptive to other areas of IT.

Question has a verified solution.

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

Slowly Changing Dimension Transformation component in data task flow is very useful for us to manage and control how data changes in SSIS.
In this article we will learn how to fix  “Cannot install SQL Server 2014 Service Pack 2: Unable to install windows installer msi file” error ?
Viewers will learn how the fundamental information of how to create a table.
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.
Suggested Courses

741 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